将子集突变值替换回 dplyr R 中的主数据集



我要做的是从主数据集中过滤出一个子集,修改值,然后将它们替换回主数据集。例如:

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_elseifelse

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

最新更新