1
votes

I have a vector with 10000+ entries, approximately 4000 of them are zeros. I want to add random values to those entries which are NOT zero. I know how to find out which indices are zero, but how can I make the addition?. For example consider this vector with only 10 indices

v <- c(0, 0.1, 0, 0, 5, 0,3, 0.8, 0, 4)
v_notzero <- which(v != 0) #extracting the non-zero entries
[1]  2  5  7  8 10
length(v_notzero)
[1] 5

now I know both the indices where v is not zero as well as the amount of entries which are non-zero. So I would like to create a random vector, which is filled with zeros at the same indices as v, and filled with random variables at v_notzero. How can I do this?

rand <- rnorm(5)
2

2 Answers

0
votes

You can reassign the values using your variable 'v_notzero' like this:

v <- c(0, 0.1, 0, 0, 5, 0,3, 0.8, 0, 4)
v_notzero <- which(v != 0) #extracting the non-zero entries

### Assign random numbers ranging from 1 to 10 ###
v[v_notzero] <- runif(length(v_notzero), 1, 10)
0
votes

Another concise way could be achieved using sample, rnorm or runif. sample should be used to select random value form a list and runif should be used to select value between a range. rnorm can be used for normal distribution. Example using sample and rnorm

v <- c(0, 0.1, 0, 0, 5, 0,3, 0.8, 0, 4)

v[ v != 0 ] <- sample(1:10, length(v[ v != 0 ]), replace = TRUE)

v
#[1]  0  3  0  0 10  0 10  3  0  7

v[ v != 0 ] <- rnorm(length(v[ v != 0 ]))
v
#[1]  0.0000  0.5965  0.0000  0.0000  1.6321  0.0000 -0.0732 -0.9436  0.0000 -1.2574