jeudi 1 mars 2018

R Generating vector w/ random integers in a fixed range with defined sum

I am trying to put together code which generates a vector any length, containing only randomized integer values within the range 0 to 3 and which total sum is always equal to 100.

I came up with the following code:

#Creating variables
x <- NULL
y_vec <- NULL

while(sum(y_vec) < 100) {
x <- sample(0:3,1)
y_vec <- c(y_vec, x) 
if(sum(y_vec) > 100) {
y_vec <- y_vec[-length(y_vec)]
} }

#Checking on the result
sum(y_vec)
y_vec

However, I do suppose there is an easier code for this problem. But so far I could not figure out any other way.




Aucun commentaire:

Enregistrer un commentaire