我想更新新列中的值。
这是我的数据:
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/