0

Just a quick question here: I created a matrix full of random numbers in which each row sums to 100. However, it includes negative numbers. I would like it so that the matrix only includes positive numbers between 0 and 100 in each row.

I have tried the following function:

matrix <- t(replicate(30,{x <- runif(3, 0, 50); y <- c(x, 100 - sum(x)); sample(y/sum(y) * 100)}))

I tried changing the min, which should be equal to 0 right now (and the max is 50), but that didn't work. What am I missing?

Thank you in advance.

Ama O
  • 47
  • 2
  • 1
    Perhaps a quibble or perhaps a point, but if a bunch of numbers sum to 100, then they aren't random. They do have a constraint.In particular, if your row size is N and you give me the first (N-1) numbers, I can 'predict' the Nth number. – meh Jun 05 '19 at 19:51
  • @Aginensky true! – Ama O Jun 05 '19 at 19:54

1 Answers1

0

Just scale first then sample.

mat <- t(replicate(30, {
  x <- runif(4, 0, 50)
  sample(x/sum(x) * 100)
  }))

any(mat < 0)
#[1] FALSE

all(rowSums(mat) == 100)
#[1] TRUE

I have changed the matrix name to mat because matrix is the name of a base R function.

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
  • Thank you, Rui Barradas. After comparing my function's output to yours, I think the problem (or at least part of the problem) was that I was using sample(y/sum(y)) instead of sample(x/sum(x)). I tried your solution and it worked. Thanks again! – Ama O Jun 05 '19 at 20:12