[英]How to use ifelse using mutate to get a new column in R
A simple sample of my data is shown below我的数据的一个简单示例如下所示
Id xy 12 Yellow Yellow 13 Yellow Blue 10 Blue Yellow 14 Blue Blue 19 Yellow Yellow
And I want to get this我想得到这个
Id xyz 12 Yellow Yellow Y 13 Yellow Blue N 10 Blue Yellow N 14 Blue Blue N 19 Yellow Yellow Y
When x and y are only Yellow, I get Y, else N for the z column当 x 和 y 只是黄色时,我得到 Y,否则 z 列的 N
I have tried this, but it does not help me.我试过这个,但它对我没有帮助。
dat%>% mutate(z=ifelse(x=="Yellow") & (ifelse(y=="yellow")),"Y","N")
We don't need two ifelse
.我们不需要两个
ifelse
。 Also, the ifelse
for first and second only had the 'test' condition, without the 'yes' or 'no' ie According to ?ifelse
, usage is此外,第一个和第二个的
ifelse
只有“测试”条件,没有“是”或“否”,即根据?ifelse
,用法是
ifelse(test, yes, no)
ifelse(测试,是,否)
In the OP's post, the ifelse
got closed after the test
condition在 OP 的帖子中,
ifelse
在test
条件后关闭
ifelse(y=="yellow")
^test condition
For multiple elements, instead of ==
, can use %in%
对于多个元素,而不是
==
,可以使用%in%
dat$z <- c("N", "Y")[Reduce(`&`, lapply(dat[-1], `%in%`, c('yellow', 'Yellow'))) + 1]
dat$z
#[1] "Y" "N" "N" "N" "Y"
Does this work?这行得通吗?
dat %>% mutate(z=ifelse(x=="Yellow" & y == "Yellow", "Y", "N"))
Or maybe this:或者也许是这样:
dat %>% mutate(z=ifelse(tolower(x)=="yellow" & tolower(y) == "yellow", "Y", "N"))
Here is one base R option without ifelse
这是一个没有
ifelse
的基本 R 选项
transform(
df,
z = c("N", "Y")[1 + (rowSums(cbind(x, y) == "Yellow") == 2)]
)
which gives这使
Id x y z
1 12 Yellow Yellow Y
2 13 Yellow Blue N
3 10 Blue Yellow N
4 14 Blue Blue N
5 19 Yellow Yellow Y
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.