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

From: Nordlund, Dan (DSHS/RDA) <NordlDJ_at_dshs.wa.gov>
Date: Thu, 24 Jul 2008 09:04:54 -0700

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



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 - 16:08:36 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 - 17:32:17 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.

list of date sections of archive