使用 dplyr 有条件地替换列中的值 [英] Using dplyr to conditionally replace values in a column

查看:21
本文介绍了使用 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

我想做的是将其替换为两个因素 - 糖果"和非糖果".我可以用 Python/Pandas 做到这一点,但似乎无法找出基于 dplyr 的解决方案.谢谢!

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!

推荐答案

假设您的数据框是 dat 并且您的列是 var:

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

dat = dat %>% mutate(candy.flag = factor(ifelse(var == "Candy", "Candy", "Non-Candy")))

这篇关于使用 dplyr 有条件地替换列中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆