方法1
简单使用
pmax
和
max.col
函数来标识最大值和列。
library(dplyr)
df %>% mutate(max = pmax(a,b), type = colnames(df)[max.col(df[,3:4]) + 2 ])
方法2
或者首先将数据重新格式化为“长”格式,以便于操作。然后使用
mutate
提取
max
值和名称。最后将其改回“宽”格式并
relocate
根据你的目标列。
df %>%
pivot_longer(a:b, names_to = "colname") %>%
group_by(lon, lat) %>%
mutate(max = max(value),
type = colname[which.max(value)]) %>%
pivot_wider(everything(), names_from = "colname", values_from = "value") %>%
relocate(max, type, .after = b)
输出
# A tibble: 4 Ã 6
# Groups: lon, lat [4]
lon lat a b max type
<dbl> <dbl> <dbl> <dbl> <dbl> <chr>
1 102 31 4 5 5 b
2 103 32 3 2 3 a
3 104 33 7 4 7 a
4 105 34 6 9 9 b