vendredi 20 octobre 2023

Let R randomly create a vector within specific requirements

I want R to create a vector for me that has length 15, each of the 15 values being in the range 0-100 and together adding up to 100. So an example outcome could be:

`[12, 25, 2, 0, 6, 17, 2, 4, 1, 8, 11, 3, 5, 0, 4]`

or

`[0, 0, 0, 1, 0, 4, 0, 0, 2, 0, 92, 0, 0, 1, 0]`

I would like to be able to change the length, the sum and the range of values of the vector for later use. Also I want the outcome to be 'random' so that I can repeat it multiple times and getting a different vector every time. (I have been searching for similar questions on some forums but without success unfortunately, but I feel it should not be too difficult)

I got this from someone else asking a similar question:

rand.vect.with.total <- function(min, max, total) {   
  x <- sample(min:max, total, replace=TRUE)       #generate random numbers  
  sum.x <- table(x)                               #count numbers   
  out = vector()   
  for (i in 1:length(min:max)) {     
  out[i] <- 
  sum.x[as.character(i)]   
  }   
  out[is.na(out)] <- 0   
  return(out) 
}

But then found out that it gives a vector with different length every time. I want the length of the vector to be constant and set by the function but I can't seem to make it work.




Aucun commentaire:

Enregistrer un commentaire