Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dplyr to conditionally replace values in a column

Tags:

r

dplyr

I have an example data set with a column that reads somewhat like this:

Candy Sanitizer Candy Water Cake Candy Ice Cream Gum Candy Coffee 

What I'd like to do is replace it into just two factors - "Candy" and "Non-Candy". I can do this with Python/Pandas, but can't seem to figure out a dplyr based solution. Thank you!

like image 959
user2762934 Avatar asked Feb 24 '16 18:02

user2762934


People also ask

How do I replace a specific value in a column in a DataFrame in R?

Method 1: Using Replace() function. replace() function in R Language is used to replace the values in the specified string vector x with indices given in list by those given in values.

How do I change the value of a dplyr?

Use mutate() and its other verbs mutate_all() , mutate_if() and mutate_at() from dplyr package to replace/update the values of the column (string, integer, or any type) in R DataFrame (data. frame). For more methods of this package refer to the R dplyr tutorial.

What does %>% do in dplyr?

%>% is called the forward pipe operator in R. It provides a mechanism for chaining commands with a new forward-pipe operator, %>%. This operator will forward a value, or the result of an expression, into the next function call/expression. It is defined by the package magrittr (CRAN) and is heavily used by dplyr (CRAN).


1 Answers

In dplyr and tidyr

dat %>%      mutate(var = replace(var, var != "Candy", "Not Candy")) 

Significantly faster than the ifelse approaches. Code to create the initial dataframe can be as below:

library(dplyr) dat <- as_data_frame(c("Candy","Sanitizer","Candy","Water","Cake","Candy","Ice Cream","Gum","Candy","Coffee")) colnames(dat) <- "var" 
like image 86
leerssej Avatar answered Oct 10 '22 11:10

leerssej