Home > database >  Replace column with corresponding value of max value from another column
Replace column with corresponding value of max value from another column

Time:01-29

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.

Thanks

CodePudding user response:

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
  •  Tags:  
  • Related