[R] different functions on different vector subsets

Prof Brian Ripley ripley at stats.ox.ac.uk
Thu Nov 10 18:32:45 CET 2005


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
>
> 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.

What do you think the NA value in

> a > 0
[1]    NA  TRUE  TRUE  TRUE FALSE FALSE FALSE

means?  Should you replace a[1] or not?  You are saying you don't know, so 
what is R to do?  It tells you to make up your mind.

Try

ind <- !is.na(a) & a > 0
a[ind] <- 2^a[ind]
ind <- !is.na(a) & a < 0
a[ind] <- (-1)/2^a[ind]

or use ifelse as in

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

which is a lot more elegant.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list