I want to update values in a new column.
Here's my data :
people<- c("father", "parents", "father", "children", "girl", "boy", "grand father", "grand mother", "grandparents" )
dataset0 <- data.frame(people)
dataset0
And the output :
father
parents
father
children
girl
boy
grand father
grand mother
grandparents
Expected output :
people people_update
father parents
parents parents
father parents
children children
girl children
boy children
grand father grandparents
grand mother grandparents
grandparents grandparents
I tried to use replace()
dataset <- dataset0 %>%
mutate(people_update = replace(people, people =="girl", "children")) %>%
mutate(people_update = replace(people, people =="boy", "children"))
dataset
but this doesn't work. The second mutate()
command cancels the first mutate()
command.
Try case_when
to specify multiple replacements. It is more concise than multiple ifelse
statement.
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_
))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With