下面是我的数据的一个简单示例
Id x y
12 Yellow Yellow
13 Yellow Blue
10 Blue Yellow
14 Blue Blue
19 Yellow Yellow
我想要得到这个
Id x y z
12 Yellow Yellow Y
13 Yellow Blue N
10 Blue Yellow N
14 Blue Blue N
19 Yellow Yellow Y
当x和y只为黄色时,我得到z列的Y,否则N
我试过了,但对我没有帮助。
dat%>% mutate(z=ifelse(x=="Yellow") & (ifelse(y=="yellow")),"Y","N")
发布于 2021-02-23 22:28:09
这行得通吗?
dat %>% mutate(z=ifelse(x=="Yellow" & y == "Yellow", "Y", "N"))或者这个:
dat %>% mutate(z=ifelse(tolower(x)=="yellow" & tolower(y) == "yellow", "Y", "N"))发布于 2021-02-23 22:02:41
我们不需要两个ifelse。此外,第一和第二的ifelse只有“测试”条件,没有“是”或“否”,也就是说,根据?ifelse,用法是
ifelse(测试,是,否)
在OP的帖子中,ifelse在test条件下被关闭
ifelse(y=="yellow")
^test condition对于多个元素,而不是==,可以使用%in%
dat$z <- c("N", "Y")[Reduce(`&`, lapply(dat[-1], `%in%`, c('yellow', 'Yellow'))) + 1]
dat$z
#[1] "Y" "N" "N" "N" "Y"发布于 2021-02-23 22:32:24
这里有一个没有ifelse的基本R选项
transform(
df,
z = c("N", "Y")[1 + (rowSums(cbind(x, y) == "Yellow") == 2)]
)这给
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 Yhttps://stackoverflow.com/questions/66341731
复制相似问题