user2762934 user2762934 -4 years ago 209
R Question

Using dplyr to conditionally replace values in a column

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!

Answer Source

Assuming your data frame is dat and your column is var:

dat = dat %>% mutate(candy.flag = factor(ifelse(var == "Candy", "Candy", "Non-Candy")))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download