r - 如何更新 dplyr 管道中的值?

标签 r dplyr

我想更新新列中的值。

这是我的数据:

people<- c("father", "parents", "father", "children", "girl", "boy", "grand father", "grand mother", "grandparents" ) 
dataset0 <- data.frame(people)
dataset0

和输出:
father              
parents             
father              
children                
girl                
boy             
grand father                
grand mother                
grandparents

预期输出:
 people           people_update

father            parents   
parents           parents   
father            parents   
children          children
girl              children
boy               children
grand father      grandparents          
grand mother      grandparents      
grandparents      grandparents

我尝试使用 replace()
dataset <- dataset0 %>%
   mutate(people_update = replace(people, people =="girl", "children")) %>%
   mutate(people_update = replace(people, people =="boy", "children")) 
 dataset

但这不起作用。第二个mutate()命令取消第一个 mutate()命令。

最佳答案

试试 case_when指定多个替换。比多重更简洁ifelse陈述。

library(dplyr)

dataset <- dataset0 %>%
  mutate(people_update = case_when(
    people %in% c("father", "parents")                            ~ "parents",
    people %in% c("children", "girl", "boy")                      ~ "children",
    people %in% c("grandparents", "grand father", "grand mother") ~ "grandparents",
    TRUE                                                          ~ NA_character_
  ))

关于r - 如何更新 dplyr 管道中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44805320/

相关文章:

r - 自定义 `sliderInput()` 外观

r - 如何聚合字符和数值而不收到无效字符错误

r - 如何使用 dplyr 在 R 中查找第一个值的列?

r - 如何使用 dplyr 根据列的子集中的任何一个是否为 NA 创建新列

r - 使用 [dplyr] 按行添加数据帧

r - 如何在线性回归中手动计算 t 统计量的 p 值

r - 基于相邻列最大值的值

r - 使用 data.table 中的列名选择多个列范围

r - 如何使用 dplyr 使用非标准评估来评估构造的字符串?

通过R中的符号链接(symbolic link)读取数据