I want to calculate the following condition using dplyr
a) When the normal minimum temperature is equal to 10°C or more.
Cold Wave: Departure from normal is -5°C to -6°C.
Severe Cold Wave: Departure from normal is -7°C or less
b) When the normal minimum temperature is less than 10°C.
Cold Wave: Departure from normal is -4°C to -5°C.
Severe Cold Wave: Departure from normal is -6°C or less.
I am using the following code
library(tidyverse)
set.seed(123)
df <- data.frame("Date"= seq(from = as.Date("1970-1-1"), to = as.Date("2000-12-31"), by = "day"),
"Station1" = runif(length(seq.Date(as.Date("1970-1-1"), as.Date("2000-12-31"), "days")), 10, 30),
"Station2" = runif(length(seq.Date(as.Date("1970-1-1"), as.Date("2000-12-31"), "days")), 11, 29),
"Station3" = runif(length(seq.Date(as.Date("1970-1-1"), as.Date("2000-12-31"), "days")), 8, 28))
#Calculation of normal minimum temperature
df_summarise_all <- df %>%
as_tibble() %>% # for easier viewing
mutate(day = format(as.Date(df$Date, format='%Y-%m-%d'), format='%m-%d')) %>%
group_by(day) %>%
summarise_all(list(mean)) %>%
pivot_longer(cols = -c(Date, day), names_to = "variable", values_to = "value")
#Identification of days fulfilling the condition for cold wave
df_out <- df %>%
as_tibble() %>% # for easier viewing
mutate(day = format(as.Date(df$Date, format='%Y-%m-%d'), format='%m-%d')) %>%
tidyr::pivot_longer(cols = -c(Date, day),
names_to = "Stations", values_to = "MinT") %>%
left_join(df_summarise_all %>% rename(mean_MinT = value),
by = c('day' = 'day', 'Stations' = 'variable')) %>%
mutate(is_coldwave = zoo::rollapplyr(MinT < (ifelse(mean_MinT < 10, mean_MinT - 4, mean_MinT - 5)),
1, all, fill = NA))
I could not implement the condition -5°C to -6°C and -4°C to -5°C. How can this be achieved using dplyr
?
See Question&Answers more detail:
os