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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With