Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update values in a dplyr pipe?

Tags:

r

dplyr

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.

like image 926
Wilcar Avatar asked Jun 28 '17 14:06

Wilcar


1 Answers

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_
  ))
like image 155
www Avatar answered Sep 28 '22 21:09

www