Reputation: 1848
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
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
Namely z
must be outputed like below:
ID z
1 0
2 1
3 1
4 1
5 1
6 0
7 1
8 1
9 1
10 0
11 1
How can I do this using R? ifelse
statement seem to me so complex with these conditions.
Upvotes: 1
Views: 81
Reputation: 263321
I dragged your conditions to my workspace and lightly editted them to make a Boolean calculation by replacing =
with ==
; and
with &
; and otherwise
with the negation of the two conditions, . The conditionals are 0 when FALSE and 1 when TRUE so act as selectors. Could also have used nested ifelse
functions, but I often find them messy. In this case Jilber proved me misguided (but not wrong.):
dat$z <- with(dat, (x1==1 & x2==0 & y<0.5)*x2+
(x1==0 & x2==1 & y>0.5)*x2+
(!(x1==1 & x2==0 & y<0.5) & !(x1==0 & x2==1 & y>0.5))*x1)
> dat
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
Upvotes: 3
Reputation: 61154
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
Upvotes: 3