Re: [R] a strange behavior with ifelse

From: Jim Lemon <jim_at_bitwrit.com.au>
Date: Sat, 09 Apr 2011 19:50:21 +1000

On 04/09/2011 03:56 AM, wgu wrote:
> I have used R for years but run into a seemingly simple problem involving 'ifelse'. condensed code like this
>
> a=c(2,NA,NA,NA,2,2,NA,2,NA,2)
> b=c(NA,1,1,NA,2,2,2,2,2,2)
>
> #I want to combined a and b into c so that c would be a valid number either a or b is not missing
>
> c=ifelse(a==1|b==1,1,ifelse(a==2|b==2,2,NA))
> cbind(a,b,c)
>
> a b c
> [1,] 2 NA NA
> [2,] NA 1 1
> [3,] NA 1 1
> [4,] NA NA NA
> [5,] 2 2 2
> [6,] 2 2 2
> [7,] NA 2 NA
> [8,] 2 2 2
> [9,] NA 2 NA
> [10,] 2 2 2
>
> look at rows 1, 7 and 9, c supposes to be 2 but got NA instead. seemingly, the second 'ifelse' doesn't perform as it supposes.
>
> my R version is 2.12.2
>
> any suggestion

Hi wgu,

c<-ifelse(is.na(a),b,a)

Jim



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. Received on Sat 09 Apr 2011 - 09:55:32 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 09 Apr 2011 - 10:00:28 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive