[R] ifelse choices in a data.frame?

Daniel Nordlund djnordlund at verizon.net
Sun Jul 19 23:32:24 CEST 2009


> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Mark Knecht
> Sent: Sunday, July 19, 2009 2:18 PM
> To: r-help
> Subject: [R] ifelse choices in a data.frame?
> 
> 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

Mark,

Why can't you use ifelse() ?

 DF$g <- with(DF, ifelse(Test,c*d,c+d))

Have I missed something in what you are doing?

Dan

Daniel Nordlund
Bothell, WA USA




More information about the R-help mailing list