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
NA
while subsetting and assigning only if you have more than one value on RHS... I.e.x[c(NA, 1)] <- 100
andx[NA] <- 100
will both work, whilex[c(NA, 1)] <- 100:101
orx[NA] <- 100:101
won'tx[x>=5 & !is.na(x)] <- c(1:8)[x>=5 & !is.na(x)] ; x[x<5 & !is.na(x)] <- (c(1:8)*10)[x<5 & !is.na(x)]