Kunzler, Andreas
2008-Jul-24 12:09 UTC
[R] NAs - NAs are not allowed in subscripted assignments
Dear List, I ran into some trouble handling missing values. 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 So I tried to exclude NAs pat<-c((a[b==1]<2 & is.na(a[b==1])==F)| (a[b==1]>3 & is.na(a[b==1])==F)) this is a logical vector a[b==1][pat==T] <-NA But it did not help Even if I have a look at a[b==1][pat==T] [1] 1 4 4 1 All I want to do is change those values to NA. Is it possible that my mistake is caused by not understanding vector[logic operation a][logic operation b] I thought it is pretty much the same as x <- vector[logic operation a] x[logic operation b] I hope someone can help me Thanks
Richard.Cotton at hsl.gov.uk
2008-Jul-24 13:23 UTC
[R] NAs - NAs are not allowed in subscripted assignments
> I ran into some trouble handling missing values. > > 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 assignmentsYou 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 ------------------------------------------------------------------------ ATTENTION: This message contains privileged and confidential inform...{{dropped:20}}
Carl Witthoft
2008-Jul-24 21:26 UTC
[R] NAs - NAs are not allowed in subscripted assignments
This may not be exactly what the OP wanted, but it may be easier to plow the original vectors a and b thru something like > alogic <-rle(!is.na(as.logical(a))) which returns a bunch of lengths and strings of TRUEs and FALSEs . Then play with alogic and blogic (created similarly to alogic), comparing to or multiplying them by a and b, and so on.
Seemingly Similar Threads
- Error: NAs are not allowed in subscripted assignments: change from R.1.9
- NAs are not allowed in subscripted assignments
- NAs are not allowed in subscripted assignments
- predict.fda - NAs are not allowed in subscripted assignments
- Manipulate Data (with regular expressions)