R dplyr get name of which.min rowwise

非 Y 不嫁゛ 提交于 2019-12-07 07:30:31

This seems kind of (well, actually very) clunky but...

DF %>% 
  mutate(y = apply(.[,2:4], 1, function(x) names(x)[which.min(x)]))
   id x1 x2 x3  y
1   1  2  0  5 x2
2   2  4  1  3 x2
3   3  5  2  4 x2
4   4  3  6  5 x1
5   5  6  7  8 x1
6   6  4  6  3 x3
7   7  3  0  4 x2
8   8  6  8  2 x3
9   9  7  2  5 x2
10 10  7  2  6 x2

Here's another approach.. I didn't run any benchmark but my guess is that it would perform better than using apply or rowwise.

DF %>% 
  mutate(y = names(.)[max.col(.[2:4]*-1)+1L])
#    id x1 x2 x3  y
# 1   1  2  0  5 x2
# 2   2  4  1  3 x2
# 3   3  5  2  4 x2
# 4   4  3  6  5 x1
# 5   5  6  7  8 x1
# 6   6  4  6  3 x3
# 7   7  3  0  4 x2
# 8   8  6  8  2 x3
# 9   9  7  2  5 x2
# 10 10  7  2  6 x2

The *-1 is because we want the min instead of the max column and +1 because we only look at columns 2:4 but need the correct column names in return.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!