R:对于每一行,找到具有最高值的列的列索引

Sta*_*t-R 1 r dplyr data.table

我正在尝试获取所选列中具有最高值的列的索引。当尝试使用 时dplyr,我的尝试没有给我正确的结果。

library(dplyr);library(magrittr)
DF1 <- data.frame(Factor1 = c(1,2,4),Factor2 = c(3,1,1),Factor3 = c(9,1,0)) %>% 
    mutate(max_ind = which.max(c(.$Factor1,.$Factor2,.$Factor3))) %>% print
          Factor1 Factor2 Factor3 max_ind
        1       1       3       9       7
        2       2       1       1       7
        3       4       1       0       7
Run Code Online (Sandbox Code Playgroud)

错误在哪里?为什么dplyr会有这样的行为。我可能应该使用rowwise,但这似乎不是最好的方法。有想过如何做到这一点base吗?tidyversedata.table

Edit-1(其他一些尝试)

通过 sapply 我得到了这个:

DF1 <- data.frame(Factor1 = c(1,2,4),Factor2 = c(3,1,1),Factor3 = c(9,1,0)) %>%
+   mutate(max_ind = which.max(c(Factor1,Factor2,Factor3)),
+          max_ind2 = sapply(X = ., function(x) which.max(c(x[Factor1],x[Factor2],x[Factor3])))) %>% print
  Factor1 Factor2 Factor3 max_ind max_ind2
1       1       3       9       7        4
2       2       1       1       7        1
3       4       1       0       7        1
Run Code Online (Sandbox Code Playgroud)

但在这里我看到第一行有 4,而它应该是 3。

编辑2

我也在寻找一种解决方案,我们可以指定用于比较的列 ( which.max)

编辑3

所有basepurrr::mapdplyr::mutate示例均有效。

#R>DF1 <- data.frame(Factor1 = c(1,2,4,1),Factor2 = c(3,1,1,6),Factor3 = c(9,1,0,4)) 
#R>DF1 %>% mutate(max_ind_purrr = pmap(.l = list(Factor1,Factor2,Factor3),~which.max(c(...)))) %>% print()
  Factor1 Factor2 Factor3 max_ind_purrr
1       1       3       9             3
2       2       1       1             1
3       4       1       0             1
4       1       6       4             2
#R>DF1 %>% mutate(max_ind_dplyr=max.col(DF1[,1:3]))
  Factor1 Factor2 Factor3 max_ind_dplyr
1       1       3       9             3
2       2       1       1             1
3       4       1       0             1
4       1       6       4             2
#R>DF1 <- transform(DF1,max_ind_base=apply(DF1[, c('Factor1','Factor2','Factor3')],1,which.max))%>% print
  Factor1 Factor2 Factor3 max_ind_base
1       1       3       9            3
2       2       1       1            1
3       4       1       0            1
4       1       6       4            2
Run Code Online (Sandbox Code Playgroud)

Chr*_*ris 5

我认为您要求进行逐行比较以查找包含该行最大值的列索引。这就是为什么 sapply 不起作用,因为默认情况下,它会向下查找列。which.max还处理向量 - 在您的情况下,您不想返回每个向量中的索引,因为它指的是向量而不是 data.frame 的行。

max这基本上就是函数和函数之间的区别pmax。的逐行版本which.maxmax.col这样你可以指定:

DF1 %>% mutate(max_ind=max.col(DF1))
Run Code Online (Sandbox Code Playgroud)

然后您可以选择要指定的列:

# only considering columns 1 and 2
DF1 %>% mutate(max_ind=max.col(DF1[,1:2]))
Run Code Online (Sandbox Code Playgroud)