示例数据:
year <- c(1990, 1991)
January <- c(1, 1)
February <- c(0, 3)
df <- data.frame(year, January, February)
year January February
1 1990 1 0
2 1991 1 3
我想获得一个具有最高温度和最高温度月份的新数据框,所以:
max_temp <- c(1,3)
month <- c("January", "February")
new_df <- data.frame(year, month, max_temp)
year month max_temp
1 1990 January 1
2 1991 February 3
只有我有400年的数据,每年有1100个月,所以重要的是这个数据运行得相当快。
我已经融化了原始数据框并按年分组数据:
melted <- melt(df, id.vars = "year")
new_frame <- melted %>%
group_by(year) %>%
summarize(max_temp = max(value))
但我还没弄明白如何获得月份。在R语言中有没有一种有效的方法可以做到这一点?
答案 0 :(得分:0)
library(tidyverse)
df_new <- df %>% gather(month, temp, January:February) %>%
group_by(year) %>% filter(temp == max(temp))