R: How to generate the highest value vectors in each row?

Let's say that in my data frame there is

> 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 different types of cars, and the columns would be probabilities for a given category V1, V2, V3.

I want to create a vector that assigns to each car, the category of which has the highest probability. For example, I would like car 1 to be connected to V3, car 2 to be connected to V1, car 3 to be connected to V2.

Any tips or hints on how I should deal with this?

+2
source share
2 answers

We can use max.colto get the column index corresponding to the highest value in each row.

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

:

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

Source: https://habr.com/ru/post/1654131/


All Articles