[R] Conditions
Val
v@|kremk @end|ng |rom gm@||@com
Wed Nov 27 00:15:19 CET 2019
HI All, I am having a little issue in my ifelse statement,
The data frame looks like as follow.
dat2 <-read.table(text="ID d1 d2 d3
A 0 25 35
B 12 22 0
C 0 0 31
E 10 20 30
F 0 0 0",header=TRUE,stringsAsFactors=F)
I want to create d4 and set the value based on the following conditions.
If d1 !=0 then d4=d1
if d1 = 0 and d2 !=0 then d4=d2
if (d1 and d2 = 0) and d3 !=0 then d4=d3
if all d1, d2 and d3 =0 then d4=0
Here is the desired output and my attempt
ID d1 d2 d3 d4
A 0 25 35 25
B 12 22 0 12
C 0 0 31 31
E 10 20 30 10
F 0 0 0 0 0
My attempt
dat2$d4 <- 0
dat2$d4 <- ifelse((dat2$d1 =="0"), dat2$d2, ifelse(dat2$d2 == "0"), dat2$d3, 0)
but not working.
Thank you.
More information about the R-help
mailing list