I want to generate a large vector of just 0's and 1's of arbitrary length. But I want at max 10 1's in the vector. (For those familiar, a 10-sparse vector of some arbitrary length) How can I do this in R/Rstudio
Asked
Active
Viewed 2,642 times
-2
-
2It is easy enough to generate a 0-1 vector with exactly 10 1's . But, you said that you want a vector with a *max* of 10 1's. Your problem is under-specified. What is the probability distribution on the possibles 1-counts (which per your problem description could be any number in the range 0,1,2,...,10). The problem with using a uniform distribution on 0-10 is that there are more binary vectors with 10 1's than e.g. 7 1's, so you would be biasing the vectors themselves if you don't bias the counts properly. – John Coleman Sep 14 '18 at 09:41
-
I don't agree that the linked question is a duplicate. That question has a twist that this question lacks (a nonuniform distribution on the probabilities of 1's occurring at various indices) and this question seems to have a twist that the other question lacks (a maximum number of 1's rather than a fixed number of 1's). – John Coleman Sep 14 '18 at 09:55
2 Answers
0
rep(0,n) #generate n zeros
sample(0:10,1) #generate random number between 0 and 10
rep(1,sample(0:10,1)) # generate random number of ones
sample(c(rep(0,n),rep(1,sample(0:10,1)))) # combine and permute

user2974951
- 9,535
- 1
- 17
- 24
0
# function that generates a 10-sparce vector
GenerateSparceVector = function(N) {
# number of 1s
n = sample(1:10,1)
# create vector
vec = c(rep(1, n), rep(0, N-n))
# randomise vector
sample(vec) }
# for reproducibility
set.seed(32)
# apply the function
GenerateSparceVector(20)
# [1] 0 0 0 1 0 0 0 0 1 0 1 1 0 1 0 0 0 0 0 1
Note that I assumed you need at least one 1
in your vector.
Every time you run it there's an equal probability of getting 1, 2, 3, ... 10 1
s in your vector.

AntoniosK
- 15,991
- 2
- 19
- 32