[R] Getting tripped up on NAs in trying to create new variable

Gabor Grothendieck ggrothendieck at gmail.com
Mon Oct 18 03:52:17 CEST 2010


On Sun, Oct 17, 2010 at 9:03 PM, Greg Blevins <gregblev at gmail.com> wrote:
> Hello R help:
>
> I have the following data:
>
> a <- c(NA, 2, 2, 3, 2, NA)
> b <- c(NA, NA, 3, NA, 1, 3)
> df <- data.frame(a, b)
>> df
>   a  b
> 1 NA NA
> 2  2 NA
> 3  2  3
> 4  3 NA
> 5  2  1
> 6  NA 3
>
> I want to create variable c such that if there is a 3 in either variable a
> or variable b, variable c is 1(rows 3, 4 & 6 below).
>
> If 3 not in a or b and a value appears in a or b, then c is 0(row 2 below).
> If NA is present in both variables, c is NA (row 1 below).
>
>   a  b   c
> 1 NA NA   NA
> 2  2 NA   0
> 3  2  3   1
> 4  3 NA   1
> 5  2  1   0
> 6  NA 3   1
>
>
> I have tried various ifelse attempts but have not hit upon the correct
> solution yet. For example,
> the following syntax throws NA for row two instead of the hope for "0".


Try this:

transform(df, c = ifelse(is.na(a) & is.na(b), NA, a %in% 3 | b %in% 3) + 0)

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list