dianaiii
dianaiii

Reputation: 89

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!

Upvotes: 1

Views: 295

Answers (2)

jblood94
jblood94

Reputation: 16981

Watch out for sample's behavior if which returns only 1 value:

> vec <- c(rep(0, 9), 1)
> sample(which(vec != 0), 1)
 [1] 4

This preserves the vector value (instead of turning it to 1) and guards against vectors with only one nonzero value using rep to guarantee sample gets a vector with more than one element:

vec[-sample(rep(which(vec != 0), 2), 1)] <- 0

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 101343

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

Upvotes: 1

Related Questions