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

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

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

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

>Solution :

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
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