Home > Software design >  find list of higgest value in row and get colum name of them
find list of higgest value in row and get colum name of them

Time:10-28

my input:

df <- data.frame("foo"=1, "bar"=2, "baz"=3, "gaz"=12, "taz"=14, "paz"=4)

I want get 3 higgest value in first row and columnname where they are. So I expect get something like this taz,gaz,paz.
I trying pmax, slice_max without success

CodePudding user response:

Here is an option with apply to do this for every row in df.

apply(df, 1, function(x) names(head(sort(x, decreasing = TRUE), 3)))

#      [,1] 
#[1,] "taz"
#[2,] "gaz"
#[3,] "paz"

If you need both the value and column name you may return a list.

apply(df, 1, function(x) {
  x <- head(sort(x, decreasing = TRUE), 3)
  list(value = as.numeric(x), name = names(x))
})

#[[1]]
#[[1]]$value
#[1] 14 12  4

#[[1]]$name
#[1] "taz" "gaz" "paz"

CodePudding user response:

If your data.frame is really only one row, you could use

library(dplyr)
library(tidyr)

df %>% 
  pivot_longer(everything()) %>% 
  slice_max(value, n = 3)

This returns

# A tibble: 3 x 2
  name  value
  <chr> <dbl>
1 taz      14
2 gaz      12
3 paz       4

Otherwise you either have to do some filtering or use a row number combined with some grouping.

  • Related