Search code examples
rvector

Change elements of a vector with a set probability


I am looking for a way to change the elements of a vector with a set probability. Take as an example this probability and vector:

p <- 0.5
v1 <- 1:10

I know that I can now change every element of the vector and add 2 to it, for example. But how can I change each element only with the probability p? So that in the end, there will be a vector in which statistically half of the elements are the same as before, and half had +2 added to them?

As I was looking for answers, all I could find was ways to calculate a probability, not set it; ways to change the entire vector; and ways to change specific elements, but not random elements chosen with a set probability.


Solution

  • You can sample the indices of v1 that are less than (p * its length) and use that to index the original vector:

    p <- 0.5
    v1 <- 1:10
    
    set.seed(123)
    
    add_2 <- sample(seq_along(v1) <= p * length(v1))
    v1[add_2] <- v1[add_2] + 2
    v1
    [1]  3  2  5  4  5  6  9  8 11 12