[R] inefficient ifelse() ?

Berend Hasselman bhh at xs4all.nl
Wed Mar 28 17:44:42 CEST 2012


On 28-03-2012, at 17:19, Manta wrote:

> I have a similar problem. I have a dataset and an element. If the element is
> equal to "YY", I want to take the first column of the dataset, otherwise I
> want to take the second column. The following does not work, as it only
> evaluates the first element. Any idea?
> 

yes.
See the description of ifelse.

> a=c("AAAXXX","BBBXXX")
> a=merge(a,c("AAA","BBB"))
> b="YY"
>> ifelse(b=="YY",a,substr(a,1,3))
> [1] "AAAXXX"

If you want the first  column of a when b=="YY" why are you doing a and not a[,1]?
If you want the second  column of a when !(b=="YY") why are you doing substr(a,1,3) and not a[,2]?

You are getting a scalar as result because of the way the ifelse function works. 

To get what you want you could do:

a[,if(b=="YY") 1 else 2]

or

acolumn <- if( b == "YY" ) 1 else 2
a[,acolumn]

or

a[,2-(b=="YY")]


Berend



More information about the R-help mailing list