[R] ifelse choices in a data.frame?

Mark Knecht markknecht at gmail.com
Sun Jul 19 23:17:37 CEST 2009


Hi,
   In my data.frame I  wanted to essentially write

If(Test) c*d else c+d

but that doesn't work. I found I could do it mathematically, but it
seems forced and won't scale well for nested logic. I have two
examples below writing columns e & f, but I don't think the code is
self-documenting as it depends on knowing that Test is a TRUE/FALSE.

   Is there a better way to do the following?

Thanks,
Mark


DF <- data.frame(cbind(a=1:4, b=1:2, c=1:8, d=1:16, e=0, f=0))
DF$Test <- with(DF, a == b)

DF$e = (DF$c*DF$d) * DF$Test + (DF$c+DF$d) * !DF$Test

DF$f = with(DF, (c*d)*Test + (c+d)*!Test)

DF




More information about the R-help mailing list