【发布时间】:2021-05-06 15:20:37
【问题描述】:
我有以下问题。 我计算了每个国家的平均温度,以及实际每日温度和平均温度之间的差异。见以下代码:
df1 <- data.frame(country = c("01", "01", "01","01", "01", "02", "02" , "03", "03","03"),
date = c("2020-01-01", "2020-01-02", "2020-01-03" , "2020-01-05", "2020-01-07", "2020-01-01", "2020-01-03", "2020-01-02", "2020-01-03", "2020-01-04"),
temperature = c(4, 3, -2, 0.1, -3, 1.5, 12, 10, 7, 5),
blabla = c(23, 41, 32, 8, 50, 27, 8, 7, 6, 12)
)
library(dplyr)
df2 <- df1 %>%
group_by(country) %>%
mutate(mean_per_country = mean(temperature))
df2$difference <- df2$temperature - df2$mean_per_country
现在我需要创建一个新列来检查同一国家/地区的连续天数是否(不限)在实际每日温度和平均温度之间存在负差或正差。有没有一种优雅的方法可以在 R 中做到这一点?
想要的输出在这里:
desired_df <- data.frame(country = c("01", "01", "01","01", "01", "02", "02" , "03", "03","03"),
date = c("2020-01-01", "2020-01-02", "2020-01-03" , "2020-01-05", "2020-01-07", "2020-01-01", "2020-01-03", "2020-01-02", "2020-01-03", "2020-01-04"),
temperature = c(4, 3, -2, 2, -3, 1.5, 12, 10, 7, 5),
blabla = c(23, 41, 32, 8, 50, 27, 8, 7, 6, 12),
mean_per_country = c(0.42, 0.42, 0.42, 0.42, 0.42, 6.75, 6.75, 7.33, 7.33, 7.33),
difference = c(3.58, 2.58, -2.42 , -0.32, -3.42 , -5.25, 5.25, 2.67, -0.333, -2.33),
new_column = c("hot",
"hot",
"", #day interrupted, therefor not "cold"
"", #day interrupted, therefor not "cold"
"", #day interrupted, therefor not "cold"
"",
"",
"",
"cold",
"cold")
)
非常感谢
【问题讨论】:
-
为什么国家01有两天热,而不是三天冷。同理,为什么03有两天冷,没有一天热?
-
@IanCampbell 因为国家 01 在 2020-01-01 和 2020-01-02 有一个积极的
difference。后来,2020-01-03 和 2020-01-05 不是连续的日子,因为缺少 2020-01-04,因此没有cold。同样,2020-01-01 中没有国家 03 的数据,因此 2020-01-02 不能是hot。现在清楚了吗? -
感谢您的澄清。