[R] ifelse choices in a data.frame?
jim holtman
jholtman at gmail.com
Sun Jul 19 23:28:13 CEST 2009
use ifelse:
> 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)
> #or
> DF$f.1 <- ifelse(DF$Test, DF$c * DF$d, DF$c + DF$d)
> head(DF)
a b c d e f Test f.1
1 1 1 1 1 1 1 TRUE 1
2 2 2 2 2 4 4 TRUE 4
3 3 1 3 3 6 6 FALSE 6
4 4 2 4 4 8 8 FALSE 8
5 1 1 5 5 25 25 TRUE 25
6 2 2 6 6 36 36 TRUE 36
>
On Sun, Jul 19, 2009 at 5:17 PM, Mark Knecht<markknecht at gmail.com> 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)
>
> 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.
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem that you are trying to solve?
More information about the R-help
mailing list