Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing specific values in vector with different samples from another vector

Tags:

r

vector

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.

like image 760
user5811685 Avatar asked Jan 19 '16 17:01

user5811685


People also ask

How do you replace a value in a vector?

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.

How do I change a specific value in a vector C++?

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 .

How do I change a vector element in R?

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.


1 Answers

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.

like image 193
David Arenburg Avatar answered Oct 19 '22 03:10

David Arenburg