Select the highest value from a set of columns of a df and get the column name of this higher value in R

2

Personal I have a table in the R where I wanted to look for the highest value in a set of columns and given this greater value, return in a new column the name of the column in which this greater value was.

For example, given the df below I wanted to look up the highest value of each row between the columns of A to F and create a new column named colunaOriginal containing the name of the column in which the largest was.

For the first line the largest value would be 100 (from column A) and the colunaA information would be in the colunaOriginal column.

df_maior_valor <- 
structure(list(A = c(100, 49, 30, 11, 7, 0, 1, 5, 7, 12), B = c(50, 
51, 20, 10, 3, 10, 2, 6, 3, 3), C = c(0, 1, 5, 2, 5, 0, 0, 2, 
1, 1), D = c(0, 0, 1, 0, 1, 0, 0, 0, 3, 2), E = c(0, 0, 0, 0, 
1, 0, 0, 0, 1, 0), F = c(0, 0, 0, 0, 1, 0, 0, 0, 0, 0)), .Names = c("A", 
"B", "C", "D", "E", "F"), row.names = c(NA, 10L), class = "data.frame")
    
asked by anonymous 02.10.2017 / 16:37

1 answer

4

Without using any extra packages, I would solve as follows. First, I find out which column has the highest value. This response is given by the column position:

x <- apply(df_maior_valor, 1, which.max)
x
 1  2  3  4  5  6  7  8  9 10 
 1  2  1  1  1  2  2  2  1  1

Then, I transform x into one factor.

x <- as.factor(x)

This factor will have numerical levels. So I need to name these levels as defined in the original problem:

levels(x) <- paste0("coluna", LETTERS[1:6])

x
      1       2       3       4       5       6       7       8       9      10 
colunaA colunaB colunaA colunaA colunaA colunaB colunaB colunaB colunaA colunaA 
Levels: colunaA colunaB colunaC colunaD colunaE colunaF

Next, I organize everything in a new data frame:

data.frame(df_maior_valor, colunaOriginal=x)
     A  B C D E F colunaOriginal
1  100 50 0 0 0 0        colunaA
2   49 51 1 0 0 0        colunaB
3   30 20 5 1 0 0        colunaA
4   11 10 2 0 0 0        colunaA
5    7  3 5 1 1 1        colunaA
6    0 10 0 0 0 0        colunaB
7    1  2 0 0 0 0        colunaB
8    5  6 2 0 0 0        colunaB
9    7  3 1 3 1 0        colunaA
10  12  3 1 2 0 0        colunaA
    
02.10.2017 / 17:47