如何select每行(不是所有列)的最大值并变异R中的最大值和名称的2列?

How to select the max value of each row (not all columns) and mutate 2 columns which are the max value and name in R?

这是原始数据框。我想知道 'a' 和 'b' 之间的最大值,以及 mutate 最大值和变量名称作为两列。

df <- data.frame(lon = c(102,103,104,105),
                 lat = c(31,32,33,34),
                 a = c(4,3,7,6),
                 b = c(5,2,4,9))

目标数据框是这样的

dftarget <- data.frame(lon = c(102,103,104,105),
                       lat = c(31,32,33,34),
                       a = c(4,3,7,6),
                       b = c(5,2,4,9),
                       max = c(5,3,7,9),
                       type = c('b','a','a','b'))

方法一

只需使用pmaxmax.col函数来识别最大值和列。

library(dplyr)

df %>% mutate(max = pmax(a,b), type = colnames(df)[max.col(df[,3:4]) + 2 ])

方法二

或者首先 re-shape 将您的数据转换为“长”格式以便于操作。然后使用 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