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

Nordlund, Dan (DSHS/RDA) NordlDJ at dshs.wa.gov
Thu Jul 24 18:04:54 CEST 2008


> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Kunzler, Andreas
> Sent: Thursday, July 24, 2008 7:45 AM
> To: Richard.Cotton at hsl.gov.uk
> Cc: r-help at r-project.org; r-help-bounces at r-project.org
> Subject: Re: [R] NAs - NAs are not allowed in subscripted assignments
> 
> 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[][] ?
> 
> 
> 
<<<snip>>>

I played a bit with this and haven't worked out all the nuances of indexing with logical statements, but I think this will do what you want.

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

Hope this is helpful,

Dan

Daniel J. Nordlund
Washington State Department of Social and Health Services
Planning, Performance, and Accountability
Research and Data Analysis Division
Olympia, WA  98504-5204
 
 



More information about the R-help mailing list