I have a vector "a" with integer values, some of which might have become 0 due to other parts of code that are running. I would like to replace the occurrences of 0 in this vector with a random sample from another vector "b" that I have. However, if there are multiple 0 values in "a", I would like them to all different samples from "b". So for instance:
a <- c(1, 2, 3, 0, 0, 0)
b <- 1:100
I would like the last three 0 values of "a" to be replaced with random values within "b", but I would like to avoid using 1, 2, or 3. Those are already in a.
Currently, I am using a while loop, so:
while(0 %in% a) {
s = sample(1, b)
while(s %in% a) {
s = sample(1, b)
}
a[a==0][1] = s
}
Is there a better way to do this? it seems like this double while loop might take a long time to run.
The replacement of values in a vector with the values in the same vector can be done with the help of replace function. The replace function will use the index of the value that needs to be replaced and the index of the value that needs to be placed but the output will be the value in the vector.
1. Using std::replace_if. The best option to conditionally replace values in a vector in C++ is using the std::replace_if function. It assigns a new value to all the elements in the specified range for which the provided predicate holds true .
Replace the Elements of a Vector in R Programming – replace() Function. replace() function in R Language is used to replace the values in the specified string vector x with indices given in list by those given in values.
You could do something like the following
indx <- which(!a) # identify the zeroes locations
# Or less golfed `indx <- which(a == 0)`
a[indx] <- sample(setdiff(b, a), length(indx)) # replace by a sample from `setdiff(b, a)`
We haven't specified replace = TRUE
so the new values will be always different of each other.
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