我有这个数据集:
Year January February March April May June July August
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 2018 45 51 63 61 79 85 88 85
2 2017 51 60 65 69 75 82 86 84
3 2016 47 55 61 68 72 84 87 85
... with 20 more rows
我想得到每行的最小值和最大值对应的月份,以及最大值和最小值之间的差值。这是我的最小值和最大值代码,
x <- colnames(data)[apply(data[,c(2:9)],1,which.max)]
y <- colnames(data)[apply(data[,c(2:9)],1,which.min)]
data$MaxMonth <- x
data$MinMonth <- y
但是,它给我 Year 作为某些 which.min 函数的输出。
Year January February March April May June July August MaxMonth MinMonth Diff
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 2018 45 51 63 61 79 85 88 85 July January 43
2 2017 51 60 65 69 75 82 86 84 July Year 35
3 2016 47 55 61 68 72 84 87 85 July Year 40
... with 20 more rows
最佳答案
我们可以使用 pivot_longer
reshape 为长格式,按 'Year' 进行分组,获取对应于 'value' 的 max/min
的列名(与which.max/which.min
) 然后加入原始数据
library(dplyr)
library(tidyr)
df %>%
pivot_longer(cols = -1) %>%
group_by(Year) %>%
summarise(maxMonth = name[which.max(value)],
minMonth = name[which.min(value)]) %>%
left_join(df, .)
关于r - R 中数据集中具有最小值和最大值的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67492483/