0

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:

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

Thanks in advance.

1 Answers1

4
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
Chamkrai
  • 5,912
  • 1
  • 4
  • 14
  • 2
    Ah, very neat one, was thinking about how to do it. By the way, You may want to add a `ungroup` at the very last. – shafee Jul 12 '22 at 14:46