[R] different functions on different vector subsets

Ron Ophir ron.ophir at weizmann.ac.il
Thu Nov 10 21:04:21 CET 2005


Thanks Thomas,

"...For logical subscripts you could argue that the 
ambiguity isn't present and that if the index was NA the element should 
just be set to NA. This change might be worth making."

I see you got my point. NA should return NA no matter what the
comparison is. But any way thanks Brian, Jim, and Berton, I have leaned
a lot. It was a good practice.
Ron

Ron Ophir, Ph.D.
Bioinformatician,
Biological Services
Weizmann Institute of Science
POB 26
Rehovot 76100
Israel
e-mail: Ron.Ophir at weizmann.ac.il
Phone: 972-8-9342614
Fax:972-8-9344113
>>> Thomas Lumley <tlumley at u.washington.edu> 11/10/05 7:04 PM >>>
On Thu, 10 Nov 2005, Ron Ophir wrote:

> Hi,
> I am trying to apply two different functions on on a vector as follow:
> a<-c(NA,1,2,3,-3,-4,-6)
> if a>0 I would like to raise it by the power of 2: 2^a and if the a<0
I
> would like to have the inverse value, i.e., -1/2^a.
> so I thought of doing it two steps:
> a[a>0]<-2^[a>0]
> a[a<0]<-(-1)/2^a[a<0]
> I got the following error
> Error: NAs are not allowed in subscripted assignments
> any other ma>nupulation that I did with is.na() but did not succeed.
> What is funny that the two sides of the assignment work and return the
> same vector size:
>> 2^a[a>0]
> [1] NA  2  4  8
>> a[a>0]
> [1] NA  1  2  3

The reason NAs are not allowed in subscripted assignments is based on 
numeric rather than logical subscripts.

For numeric subscripts the problem is ambiguity about what the NA index 
should do (we know there is ambiguity because two parts of the R code
did 
different things).  For logical subscripts you could argue that the 
ambiguity isn't present and that if the index was NA the element should 
just be set to NA. This change might be worth making.


> I found a solution in term of:
> sapply(a,function(x) if (is(s.na)) NA else if (x<0) (-1)/2^x else 2^x)
> but still I would like to understand why the solution above did not
> work. I think is more ellegant.

A better general solution is

  a<-ifelse(a<0, -1/2^a, 2^a)

An alternative for this problem that is faster when a is very large is
  a<-sign(a)*2^abs(a)

 	-thomas




More information about the R-help mailing list