Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NAs are not allowed in subscripted assignments

Tags:

r

I have a simple issue, but I couldn't grasp the logic to overcome it.

I have numeric vectors with NAs and want to apply a condition-dependent operation on them.

A simple example similar to my problem is:

x <- c(1,3,5,7,NA,2,4,6)
x[x>=5] <- c(1:8)[x>=5]
x[x<5] <- (c(1:8)*10)[x<5]

It returns the error "NAs are not allowed in subscripted assignments", so I'd like to know what would be a sensible solution for that, given that running each attribution separately works as expected.

I would like to have the expected result of:

[1]  10  20  3  4 NA  60  70  8

Preferably without having to make a for loop, as this operation is already in a function for null modelling with lots of iterations that is taking ages.

Thank you in advance, Leonardo

NB. NAs mean Not Available values

like image 230
LeoRJorge Avatar asked Nov 12 '14 17:11

LeoRJorge


1 Answers

Your logic will need to also exclude NAs in the subset. See the following example. Note the subsets vectors are stored away before x is modified.

x <- c(1,3,5,7,NA,2,4,6)
subset1 <- x>=5 & !is.na(x)
subset2 <-  x<5 & !is.na(x)

x[subset1] <- which(subset1)
x[subset2] <- 10*which(subset2)
like image 196
vpipkt Avatar answered Nov 17 '22 16:11

vpipkt