本文介绍了R dplyr得到which.min rowwise的名字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我刚刚回覆了这个问题有一个 data.table 方法,并且正在努力提供一个等价的 dplyr 失败了。 它的列中有数值的简单数据框。我想使用dplyr 获取最小值的列的名称。 请注意,我知道其他解决这个问题的方法:目前我唯一的兴趣是在dplyr方法中 id x1 x2 x3 DF< - data.frame(id,x1,x2,x3) 我尝试了几种变体: DF%>%select (2:4)%>%rowwise()%>%mutate(y = function(x)names(x)[which.min(x)]) DF%>%选择(2:4)%>%rowwise()%>%mutate(y = apply(x1:x3,1,which.min(x1:x3)) / pre> 但是还没有找到一种方法来实现 dplyr -way。提示! 预期输出: DF # #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 解决方案 这似乎是一种(实际上非​​常非常)笨重但是... DF%>% mutate(y = apply(。[,2:4],1,function(x)names(x)[which.min(x)])) pre> 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 pre> I just answered this question with a data.table approach, and was working hard to provide a dplyr equivalent, but failed misserably.There's a simple data frame with numerical values in its columns. I want to get the name of the column with the minimum value using dplyr.Please notice that I'm aware of other methods to solve this problem: at the moment my only interest is in the dplyr approachid <- c(1,2,3,4,5,6,7,8,9,10)x1 <- c(2,4,5,3,6,4,3,6,7,7)x2 <- c(0,1,2,6,7,6,0,8,2,2)x3 <- c(5,3,4,5,8,3,4,2,5,6)DF <- data.frame(id, x1,x2,x3)I tried several variants of:DF %>% select(2:4) %>% rowwise() %>% mutate(y = function(x) names(x)[which.min(x)])DF %>% select(2:4) %>% rowwise() %>% mutate(y = apply(x1:x3, 1, which.min(x1:x3))but haven't found a way to do this the dplyr-way. I'll appreciate any hint!Expected output:DF## 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 解决方案 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 y1 1 2 0 5 x22 2 4 1 3 x23 3 5 2 4 x24 4 3 6 5 x15 5 6 7 8 x16 6 4 6 3 x37 7 3 0 4 x28 8 6 8 2 x39 9 7 2 5 x210 10 7 2 6 x2 这篇关于R dplyr得到which.min rowwise的名字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-20 22:38