2016-11-12 764 views
0

我想在R中創建兩個矩陣,使得矩陣x的元素應該是任意分佈的隨機數,然後計算這個2 * 2矩陣的colSums和rowSums。然後,我想以從任何分佈生成矩陣y,使得第一子集2 * 2元素是隨機的,然後第三行和列是行元素和列元素的總和,然後第四行和列是隨機的,使得rowSums和3:4的colSums等於第一個矩陣x的colSums和行Sum。我如何在R中創建兩個具有這些屬性的隨機矩陣?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 
+0

你怎麼到240秒?由於你在矩陣x中沒有第三行/列,我不明白它們來自哪裏 – David

回答

0

我正在嘗試使用正態分佈的隨機數。用從批量包裝mvrnorm()爲same.?mvrnorm更多信息

library(MASS) 

mu1 = 2 #mean for first distribution 
mu2 = 3 #mean for second distribution 
covm = matrix(c(2,1,1,1), ncol = 2) # covariance matrix 

set.seed(1000) 
x = mvrnorm(n = 2, mu = c(2,3), Sigma = covm) 
colsumx = colSums(x) 
rowsumx = rowSums(x) 


set.seed(2000) 
y = mvrnorm(n = 2, mu = c(2,3), Sigma = matrix(c(2,1,1,1), ncol = 2)) 
y = cbind(y, rowSums(y)) 
y = rbind(y, colSums(y)) 
y = rbind(y, c(colsumx - y[3,1:2], sum(colsumx) - y[3,3])) 
y = cbind(y, c(rowsumx - y[1:2,3], sum(rowsumx) - y[3,3], 0)) 

# > x 
#   [,1]  [,2] 
# [1,] 2.626924 3.357580 
# [2,] 3.867469 3.689616 
# > y 
#    [,1]  [,2]  [,3]  [,4] 
# [1,] 3.46444151 3.258343 6.722785 -0.7382805 
# [2,] 3.05148893 2.384737 5.436226 2.1208596 
# [3,] 6.51593044 5.643080 12.159011 1.3825791 
# [4,] -0.02153748 1.404117 1.382579 0.0000000 
0

我想你只需要生成兩個2x2隨機矩陣,然後所有其他值可以通過它們來獲得:

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 

結果:

> 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