Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find max value in multiple columns and add column name

I would like to find the max value in each row for a data frame and add it in a new column. I have tried this code:

#create data frame
df <- data.frame(player=c('A', 'B', 'C', 'D', 'E', 'F', 'G'),
                 points=c(28, 17, 3, 14, 3, 26, 5),
                 rebounds=c(5, 6, 4, 7, 14, 12, 9),
                 assists=c(10, 13, 7, 8, 4, 5, 8))

#add new column that contains max values
df$max_points_rebs <- pmax(df$points, df$rebounds, df$assists)

Now I would like to get a new variable with the name of the variable that contains the max value, instead of the value itself, but I don’t know how to do it.

The output that I would like is this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Player Max value
A points
B points
C assists
D points
E rebounds
F points
G rebounds

Thanks in advance.

>Solution :

library(tidyverse)

df <- data.frame(player=c('A', 'B', 'C', 'D', 'E', 'F', 'G'),
                 points=c(28, 17, 3, 14, 3, 26, 5),
                 rebounds=c(5, 6, 4, 7, 14, 12, 9),
                 assists=c(10, 13, 7, 8, 4, 5, 8))


df %>%  
  pivot_longer(-player, 
               names_to = "max_value") %>% 
  group_by(player) %>% 
  slice_max(value) %>% 
  ungroup()

# A tibble: 7 × 3
  player max_value value
  <chr>  <chr>     <dbl>
1 A      points       28
2 B      points       17
3 C      assists       7
4 D      points       14
5 E      rebounds     14
6 F      points       26
7 G      rebounds      9
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading