[R] ifelse choices in a data.frame?
Duncan Murdoch
murdoch at stats.uwo.ca
Sun Jul 19 23:26:17 CEST 2009
On 19/07/2009 5:17 PM, Mark Knecht wrote:
> 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)
Use ifelse().
DF$f <- with(DF, ifelse(a == b, c*d, c+d))
Duncan Murdoch
>
> DF
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list