复杂的多个if语句 [英] Complex multiple if statements
本文介绍了复杂的多个if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我有这样的数据框( df
)
Let I have such a dataframe (df
)
ID x1 x2 y
1 1 0 0.21
2 1 0 0.56
3 1 1 0.34
4 0 1 0.76
5 1 1 0.06
6 1 0 0.45
7 0 1 0.56
8 0 1 0.83
9 0 1 0.64
10 0 0 0.44
11 1 0 0.54
我想在中创建一个新的
符合以下条件: colunm(z)
df
I want to create a new colunm(z)
in df
which obey the below conditions:
{if(x1=1 and x2=0 and y<0.5)
then z=x2(namely 0)}
{if(x1=0 and x2=1 and y>0.5)
then z=x2(namely 1)}
else z=x1
即 z
必须如下所示:
ID z
1 0
2 1
3 1
4 1
5 1
6 0
7 1
8 1
9 1
10 0
11 1
如何使用R执行此操作? ifelse
声明似乎对我这么复杂。
How can I do this using R? ifelse
statement seem to me so complex with these conditions.
推荐答案
使用嵌套 ifelse
。考虑 df
是您的数据框,然后:
Use nested ifelse
. Consider df
is your dataframe, then:
> df$z <- with(df, ifelse(x1==1 & x2==0 & y<0.5, x2,
ifelse(x1==0 & x2==1 & y>0.5, x2,x1 )))
>
> df
ID x1 x2 y z
1 1 1 0 0.21 0
2 2 1 0 0.56 1
3 3 1 1 0.34 1
4 4 0 1 0.76 1
5 5 1 1 0.06 1
6 6 1 0 0.45 0
7 7 0 1 0.56 1
8 8 0 1 0.83 1
9 9 0 1 0.64 1
10 10 0 0 0.44 0
11 11 1 0 0.54 1
这篇关于复杂的多个if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文