pr1g114413085
pr1g114413085

Reputation: 155

Replacing subsetted mutated values back into the main dataset in dplyr R

What I'm trying to do is filter a subset out of a main dataset, modify the values and then replace them back into the main dataset. For example:

x<-diamonds %>% filter(color == "E") %>% mutate(editPrice= price/4)

So in this example I'd replace the colour "E" prices in the main "diamonds" with my "editPrice" variable, without over writing the other colour values.

My current solution is to build a unique ID for the subset and main set then right_join them based on that variable, however this incurs lots of NA's into my total dataset. For example:

x$id<- paste(x$cut,"_",x$clarity,"_",x$table)
x1<-diamonds %>% filter(color != "E")
x1$id<- paste(x1$cut,"_",x1$clarity,"_",x1$table)
right_join(x1,x,by="id")

Thanks for your help!

Upvotes: 1

Views: 102

Answers (1)

akrun
akrun

Reputation: 887068

We can use case_when

library(dplyr)
diamonds %>%
    mutate(editPrice = case_when(color == "E" ~ price/4, 
                                 TRUE ~ as.numeric(price)))

or if_else or ifelse

diamonds %>% 
      mutate(editPrice = if_else(color == "E",  price/4,  as.numeric(price)))

Upvotes: 2

Related Questions