我要做的是从主数据集中过滤出一个子集,修改值,然后将它们替换回主数据集。例如:
x<-diamonds %>% filter(color == "E") %>% mutate(editPrice= price/4)
因此,在这个例子中,我将主"钻石"中的颜色"E"价格替换为我的"editPrice"变量,而不会覆盖其他颜色值。
我目前的解决方案是为子集和主集构建一个唯一的 ID,然后根据该变量right_join
它们,但这在我的总数据集中产生了大量NA
。例如:
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")
感谢您的帮助!
我们可以使用case_when
library(dplyr)
diamonds %>%
mutate(editPrice = case_when(color == "E" ~ price/4,
TRUE ~ as.numeric(price)))
或if_else
或ifelse
diamonds %>%
mutate(editPrice = if_else(color == "E", price/4, as.numeric(price)))