I'm looking for a way to generate a series of matrices where all the column sums are equal to a specific value. I thought I could generate random matrices and check each one to filter out where colSums= value needed, but that doesn't seem to work. Also, how do we generate random matrices in R with both positive and negative values?
Asked
Active
Viewed 298 times
2
-
for the second question, you can have a look to `?runif`, eg try `runif(your_desired_number, -1, 1)` – Vincent Bonhomme May 26 '16 at 08:06
-
Please give an example of such a matrix : your question is too broad as it is. – Vincent Guillemot May 26 '16 at 08:09
-
@priya12 hello if the answer to the question solves your problem, can you click 'accept' it so that other people can benefit from it? thanks – agenis Jun 14 '16 at 07:56
1 Answers
2
You can do like this. This is a function that creates a matrix filled with random numbers from a normal distribution. Then it centers all columns to 0 and adds up the desired number.
RandomMatrixColsum = function(mycolsum=1, dim=c(10, 10), ...){
m <- matrix(rnorm(prod(dim), ...), ncol=dim[2])
ms <- scale(m, center=T, scale=F) + mycolsum/dim[1]
return(ms)
}
RandomMatrixColsum(8)
If you want to make sure to have both positive and negative values in your matrix, you can increase the standard deviation of the rnorm
by adding an argument sd=...
to the function call, or also force the sd to be equal to the mean.

agenis
- 8,069
- 5
- 53
- 102