shany shany - 25 days ago 6
R Question

Random generated matrices in R

I would like to create two matrices in R such that the elements of matrix x should be random from any distribution and then I calculate the colSums and rowSums of this 2*2 matrix.Then, I would like to generate matrix y from any distribution such that the first subset 2*2 elements are random and then the third row and column are the sum of row and column elements and then the fourth row and column are random in such a way that the rowSums and colSums of 3:4 are equal to the colSums and row Sums of first matrix x. How can I create two random matrices with these properties in R ?

x=matrix(c(100, 50, 0, 250), nrow=2)
csum1=colSums(x)
rsum1=rowSums(x)

y=matrix(c(15, 60, 75, 25,60, 25, 85, 215, 75, 85, 160, 240,
75, 165, 240, 0), ncol=4) 1
csum2=colSums(y[3:4,c(-3,-4)])
rsum2=rowSums(y[c(-3,-4),3:4])

> x
[,1] [,2]
[1,] 100 0
[2,] 50 250
> y
[,1] [,2] [,3] [,4]
[1,] 15 60 75 75
[2,] 60 25 85 165
[3,] 75 85 160 240
[4,] 25 215 240 0

Answer

I think you just need to generate two 2x2 random matrices and then all the other values can be obtained by them :

set.seed(1234) # just for reproducibility

# generate the two 2x2 matrices with your desired distribution
# (e.g. here I'm generating integers using the uniform distribution)
x <- matrix(as.integer(runif(n = 4,min=10,max=100)),nrow=2)
y22 <- matrix(as.integer(runif(n = 4,min=10,max=100)),nrow=2)

# compute col and row sums of first matrix
csumX=colSums(x)
rsumX=rowSums(x)

# initialize the 4x4 matrix with NAs and set the upper-left 2x2 corner
y <- matrix(NA,nrow=4,ncol=4)
y[1:2,1:2] <- y22

# define the values of 3rd row and colum as sum of other values
# (exluding elements on the 4th row and column)
y[1:2,3] <- colSums(y[1:2,1:2])
y[3,1:2] <- rowSums(y[1:2,1:2])
y[3,3] <- sum(y[1:2,1:2]) # by definition y[3,3] == y[3,1]+y[3,2] == y[1,3]+y[2,3]

# define first two elements of 4th row and column
y[4,1] <- csumX[1] - y[3,1]
y[4,2] <- csumX[2] - y[3,2]

y[1,4] <- rsumX[1] - y[1,3]
y[2,4] <- rsumX[2] - y[2,3]

# complete 3rd row and column values
y[4,3] <- y[4,1] + y[4,2] # these two will be equal by definition
y[3,4] <- y[1,4] + y[2,4]

# element y[4,4] (always zero ?)
y[4,4] <- 0

Result :

> x
     [,1] [,2]
[1,]   20   64
[2,]   66   66
> y
     [,1] [,2] [,3] [,4]
[1,]   87   10  154  -70
[2,]   67   30   40   92
[3,]   97   97  194   22
[4,]  -11   33   22    0