Reputation: 347
I have an vector r of length n with zeros and ones. It can't be all zero. Also I would have a vector y of length n as well but some value in y are missing based on the value zero in vector r. I have to replace the missing values in y by sample value
example if r = c(1,1,0)
the y = c(3,2,NA)
so sample one value (8) then replace NA with 8. the vector r
could have two zeros so I have to sample two values. and replace the two missing of y by the sample values.
Upvotes: 0
Views: 169
Reputation: 1237
You can convert the r
vector to booleans with as.logical
and then use that to index into the y
vector for the replacement. Specify the size
argument of sample
with the sum of the index vector for cases where there is more than one missing value. I'm sampling integers from 1:10 to illustrate this as you didn't specify what you're sampling from:
r <- c(1,1,0)
y <- c(3,2,NA)
idx <- !as.logical(r)
y[idx] <- sample(1:10, size = sum(idx))
The r
vector is kind of redundant though as you could check for NA
values in y
directly:
ifelse(is.na(y), sample(1:10), y)
Upvotes: 0