Carpa
Carpa

Reputation: 458

How to retrieve values from a column corresponding to the max values of other columns in a dataframe

I have a dataframe like this:

[,1] [,2] [,3] [,4] [,5] [,6]
 a    1    5     7    9    4
 b    2    8     2    3    5
 c    3    9     2    4    8
 d    4    2     6    1    3

And I would like to obtain the values of column [,1] based on the max values of the other columns. The result should be something like this:

[1] "d" "c" "a" "a" "c"

Thank you in advance.

Upvotes: 2

Views: 76

Answers (3)

akrun
akrun

Reputation: 887118

We can reshape to 'long' format and then slice to get the value of the first column (assuming it is a data.frame

library(dplyr)
library(tidyr)
df %>%
    pivot_longer(cols = -V1) %>%
    group_by(name) %>% 
    slice(which.max(value)) %>% 
    pull(V1)
#[1] "d" "c" "a" "a" "c"

If it is a matrix, convert to data.frame with as.data.frame

data

df <- structure(list(V1 = c("a", "b", "c", "d"), V2 = 1:4, V3 = c(5L, 
8L, 9L, 2L), V4 = c(7L, 2L, 2L, 6L), V5 = c(9L, 3L, 4L, 1L), 
    V6 = c(4L, 5L, 8L, 3L)), class = "data.frame", row.names = c(NA, 
-4L))

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 101343

You can use max.col

  • if it is a data frame df
> df[max.col(t(df[-1])),1]
[1] "d" "c" "a" "a" "c"
  • if it is a matrix m
> m[max.col(t(as.numeric(m[,-1]))),1]
[1] "d" "c" "a" "a" "c"

Data

df <- structure(list(V1 = c("a", "b", "c", "d"), V2 = 1:4, V3 = c(5L, 
8L, 9L, 2L), V4 = c(7L, 2L, 2L, 6L), V5 = c(9L, 3L, 4L, 1L), 
    V6 = c(4L, 5L, 8L, 3L)), class = "data.frame", row.names = c(NA, 
-4L))

m <- structure(c("a", "b", "c", "d", "1", "2", "3", "4", "5", "8", 
"9", "2", "7", "2", "2", "6", "9", "3", "4", "1", "4", "5", "8", 
"3"), .Dim = c(4L, 6L))

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388982

If you have a dataframe, you can use which.max to get index max value in each column and use that index to subset values from first column.

df$V1[sapply(df[-1], which.max)]
#[1] "d" "c" "a" "a" "c"

If you have matrix (which looks more likely) then all the values would turn into character because of first column, in that case you can do :

mat[apply(mat[, -1], 2, function(x) which.max(as.numeric(x))), 1]
#[1] "d" "c" "a" "a" "c"

data

df <- structure(list(V1 = c("a", "b", "c", "d"), V2 = 1:4, V3 = c(5L, 
8L, 9L, 2L), V4 = c(7L, 2L, 2L, 6L), V5 = c(9L, 3L, 4L, 1L), 
V6 = c(4L, 5L, 8L, 3L)), row.names = c(NA, -4L), class = "data.frame")

mat <- structure(c("a", "b", "c", "d", "1", "2", "3", "4", "5", "8", 
"9", "2", "7", "2", "2", "6", "9", "3", "4", "1", "4", "5", "8", 
"3"), .Dim = c(4L, 6L))

Upvotes: 3

Related Questions