# Re: [R] NAs - NAs are not allowed in subscripted assignments

From: Kunzler, Andreas <a.kunzler_at_bzaek.de>
Date: Thu, 24 Jul 2008 16:45:14 +0200

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)
 7
length(you)
 12

me
 1 1 1 1 NA NA NA
you
 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
 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

R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Thu 24 Jul 2008 - 15:25:42 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 24 Jul 2008 - 16:32:11 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.