0

I would like to use this code, which I found here: Generate N random integers that sum to M in R. I try to make every product to have a calculated function for its standard deviation.

rand_vect <- function(N, M, sd, pos.only = TRUE) {
  vec <- rnorm(N, M/N, sd)
  if (abs(sum(vec)) < 0.01) vec <- vec + 1
  vec <- round(vec / sum(vec) * M)
  deviation <- M - sum(vec)
  for (. in seq_len(abs(deviation))) {
    vec[i] <- vec[i <- sample(N, 1)] + sign(deviation)
  }
  if (pos.only) while (any(vec < 0)) {
    negs <- vec < 0
    pos  <- vec > 0
    vec[negs][i] <- vec[negs][i <- sample(sum(negs), 1)] + 1
    vec[pos][i]  <- vec[pos ][i <- sample(sum(pos ), 1)] - 1
  }
  vec
}

df <- data.frame(Product = c("A", "B", "C"), 
                   Oct = c(33, 23, 12),
                   Nov = c(23, 26, 19),
                      SD = c(2, 10, 5))

#I tried to do it like this, but it doesn't work correct:
df_new <- as.data.frame(sapply(unlist(df[c(2,3)]), rand_vect, N = 7, df$SD))

Zizou
  • 503
  • 5
  • 18
  • what results do you get? what results do you expect to get? – C8H10N4O2 Dec 05 '19 at 13:07
  • I expect oct1 and nov1 to have sd = 2, oct2 and nov2 to have sd = 10 etc. – Zizou Dec 05 '19 at 13:17
  • It might help in your searching efforts to know that there is a Dirichlet-multinomial distribution that is the discrete (integer) version of the Dirichlet distribution. It would have helped if had included the error message and/or the erroneous results from your attempted solution. https://www.google.com/search?q=cran+Dirichlet-multinomial+distribution&oq=cran+Dirichlet-multinomial+distribution – IRTFM Mar 08 '21 at 22:54

0 Answers0