Jenny Empawi
Jenny Empawi

Reputation: 27

Select highest 3 values and return row and column name in R

I would like to select top 3 highest score from a data table and return the row and column name. I have a data table named score like below.

| |a   |b   |c   |d   |
|-|----|----|----|----|
|1|10  |23  |56  |5   |
|2|34  |25  |16  |67  |
|3|9   |11  |32  |45  |
|4|29  |47  |27  |35  |
|5|48  |4   |41  |22  |

This is my expected output:

d 2
c 1
a 5

Thank you in advance.

Upvotes: 0

Views: 319

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388817

Get the data in long format and keep top 3 rows from the data.

library(tidyverse)

df %>%
  rownames_to_column('row') %>%
  pivot_longer(cols = -row) %>%
  slice_max(value, n = 3)

#  row   name  value
#  <chr> <chr> <int>
#1 2     d        67
#2 1     c        56
#3 5     a        48

Upvotes: 2

Related Questions