[R] NAs - NAs are not allowed in subscripted assignments

Kunzler, Andreas a.kunzler at bzaek.de
Thu Jul 24 16:45:14 CEST 2008


Hy Richie, thank you for the quick response.

Unfortunately my problems hold on.

Once again: 2 vectors (numeric) including NAs 
My intention: I want to replace the values of vector a that are smaller
than 2 and larger than 3 into NAs only in case vector b equals 1

a <- c(rep(seq(1,4),4),NA,NA)
b <- c(rep(seq(1,2),7),NA,NA,1,2)
 
data.frame(a,b)
    a  b
1   1  1
2   2  2
3   3  1
4   4  2
5   1  1
6   2  2
7   3  1
8   4  2
9   1  1
10  2  2
11  3  1
12  4  2
13  1  1
14  2  2
15  3 NA
16  4 NA
17 NA  1
18 NA  2


me <- a[b==1][a[b==1]<2 | a[b==1]>3]
you <- a[a[b==1]<2 | a[b==1]>3]

There are some differences
 
length(me)
[1] 7
length(you)
[1] 12

me
[1]  1  1  1  1 NA NA NA
you
[1]  1  3  1  3 NA NA NA  3  1  3 NA NA

Your vector is containing the value 3. And in our case this value would
be replaced by NA.

I belive that in this case

a[b==1]<2 | a[b==1]>3
[1]  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE    NA    NA    NA

Would be applied on the FIRST 10 values of a and then will be repeated. 

Maybe it would be possible to do something like

a[(a<2 & b==1) | (a>3 & b==1)]

Is it allowed to construct double indices like
vector[][] ?






 
> Assume 2 vectors (numeric) including NAs
> 
> a <- c(rep(seq(1,4),4),NA,NA)
> b <- c(sample(1:2,14,replace=T),NA,NA,1,2)
> 
> I want to replace the values of vector a that are smaller than 2 and
> larger than 3 into NAs only in case vector b equals 1
> 
> a[b==1][a[b==1]<2 | a[b==1]>3] <- NA
> The following error accurse:
> NAs are not allowed in subscripted assignments

You were nearly right - you just had an extra index that you didn't
need. 
Try:
a[a[b==1]<2 | a[b==1]>3] <- NA

Regards,
Richie.

Mathematical Sciences Unit
HSL



More information about the R-help mailing list