TheGoat
TheGoat

Reputation: 2877

Replace column with corresponding value of max value from another column

I would like to replace the CATEGORY column with the category corresponding to the max value in the sales column.

My data looks as follows:

df <- data.frame(CATEGORY = c("A","A","A","B","B"), SALES = c(10,20,30,40,50))

I'm looking to fill the CATEGORY variable with "B" since the max value in SALES has a CATEGORY of B

df <- data.frame(CATEGORY = c("B","B","B","B","B"), SALES = c(10,20,30,40,50))

If this can be achieved using dplyr syntax I'd be very grateful if anyone could give me a few pointers.

Upvotes: 2

Views: 691

Answers (1)

PaulS
PaulS

Reputation: 25528

A possible solution:

library(tidyverse)

df <- data.frame(CATEGORY = c("A","A","A","B","B"), SALES = c(10,20,30,40,50))

df %>% 
  mutate(CATEGORY = CATEGORY[which.max(SALES)])

#>   CATEGORY SALES
#> 1        B    10
#> 2        B    20
#> 3        B    30
#> 4        B    40
#> 5        B    50

Upvotes: 3

Related Questions