R: How to generate vectors of highest value in each row? [duplicate]

心已入冬 提交于 2019-12-12 19:14:23

问题


Let's say that my data frame contains

> DF
   V1   V2   V3  
1  0.3  0.4  0.7  
2  0.4  0.2  0.1  
3  0.2  0.8  0.3  
4  0.5  0.8  0.9   
5  0.2  0.7  0.8  
6  0.8  0.3  0.6  
7  0.1  0.5  0.4  

the rows would be the different types of automobiles, and the columns would be the probabilities for a given category of V1, V2, V3.

I want to generate a vector that assigns to each automobile the category of which it has the highest probability in. For example, I'd want automobile 1 to be associated with V3, automobile 2 to be associated with V1, automobile 3 to be associated with V2.

Any aids or hints on how I should tackle this?


回答1:


We can use max.col to get the column index that corresponds to the largest value in each row.

names(DF)[max.col(DF, "first")]
#[1] "V3" "V1" "V2" "V3" "V3" "V1" "V2"



回答2:


Another solution is:

names(DF)[apply(DF, 1, which.max)]
# [1] "V3" "V1" "V2" "V3" "V3" "V1" "V2"


来源:https://stackoverflow.com/questions/37236169/r-how-to-generate-vectors-of-highest-value-in-each-row

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