[R] NAs are not allowed in subscripted assignments

Prof Brian Ripley ripley at stats.ox.ac.uk
Thu Jan 8 18:19:59 CET 2009


On Thu, 8 Jan 2009, Rune Schjellerup Philosof wrote:

> Browse[1]> j <- c(1,2,NA)
> Browse[1]> j[j==1][-1]
> [1] NA
> Browse[1]> j[j==1][-2]
> [1] 1
> Browse[1]> j[j==1][-2] <- 2
> Error during wrapup: NAs are not allowed in subscripted assignments
>
> As far as I can see, I have no NA in the lhs (not after the second
> subscript anyway).

But, it is not 'after the second subscript'.  R evaluates from left to 
right and does not re-evaluate subscripts in the light of subexpressions.

Think of this as (E&OE, since interpreters are far better at this than 
humans)

ind <- j==1     # c(TRUE, FALSE, NA)
tmp1 <- j[ind]  # c(1, NA)
tmp1[-2] <- 2   # tmp1 = c(2, 2)
j[ind] <- tmp1  # j[(c(TRUE, FALSE, NA)] <- c(2,2)

and that last is the problematic subassignment.  You asked to assign the 
second '2' to an unknown element of 'j': if allowed that would make all 
elements NA but then the first value would be unused, so the interpreter 
would think you confused.

> Besides, I have a single value on the rhs, so it should be allowed to
> have NAs in the lhs, according to help(Extract).

But you do not on one of your subassignments.

> What am I missing?
> I can see no ambiguite as to what the result of those commands should be
> (j == c(2,2,NA)).

I suggest you refrain from using such complicated statements.  Just 
occasionally such constructs are needed for efficiency (potentially fewer 
copies) but very rarely (and only by R masters).

> -- 
> Med venlig hilsen
> Rune Schjellerup Philosof
> Videnskabelig Assistent, Statistik, SDU
>
> Telefon:  6550 3607
> Email:    rphilosof at health.sdu.dk
> Adresse: J.B. Winsløwsvej 9, 5000 Odense C

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