Search code examples
rvectorsample

R: randomly sample a nonzero element in a vector and replace other elements with 0


Suppose I have a vector

vec <- c(0, 1, 0, 0, 0, 1, 1, 1, 1, 2)

How do I random sample a nonzero element and turn other elements into 0?

Suppose the element sampled was vec[2], then the resulting vector would be

vec <- c(0, 1, 0, 0, 0, 0, 0, 0, 0, 0)

I know that I can sample the indice of one nonzero element by sample(which(vec != 0), 1), but I am not sure how to proceed from that. Thanks!


Solution

  • You can try the code below

    > replace(0 * vec, sample(which(vec != 0), 1), 1)
     [1] 0 0 0 0 0 0 0 1 0 0
    

    where

    • which returns the indices of non-zero values
    • sample gives a random index
    • replace replaces the value to 1 at the specific index