Skip to content

NAs are not allowed in subscripted assignments

2 messages · Rune Schjellerup Philosof, Brian Ripley

#
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).
Besides, I have a single value on the rhs, so it should be allowed to
have NAs in the lhs, according to help(Extract).

What am I missing?
I can see no ambiguite as to what the result of those commands should be
(j == c(2,2,NA)).
#
On Thu, 8 Jan 2009, Rune Schjellerup Philosof wrote:

            
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.
But you do not on one of your subassignments.
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).