Martin Smith
Martin Smith

Reputation: 87

Creating random matrix with rules in R

I need to create a random matrix from the values below which will contain two basic rules:

1) Each column must contains only one value where remaining will be zeros and

2) each row must be occupied by only one value.

# create dummy matrix
B = matrix( 
  c(83, 101, 75, 182, 150, 199,
    218,  80,   90, 138,    249,    299,
    113,  171,  146,    226,    40.4,   78,
    314,    116,    186,    33.2,   345,    196,
    327,    189,    199,    109,    359,    281,
    430,    292,    302,    232,    461,    404    
  ), ncol=6, nrow=6)
# Transpose
t(B)
# names for cols and rows
colnames(B) <- c("x1",  "x2",   "x3",   "x4",   "x5",   "x6")
rownames(B) <- c("y1",  "y2",  "y3",    "y4",   "y5",   "y6")

Every possible combination of that arrangement is the output

    x1  x2  x3  x4  x5  x6
y1  83  0   0   0   0   0
y2  0   0   90  0   0   0
y3  0   171 0   0   0   0
y4  0   0   0   0   345 0
y5  0   0   0   109 0   0
y6  0   0   0   0   0   404

and e.g.

    x1  x2  x3  x4  x5  x6
y1  0   101 0   0   0   0
y2  218 0   0   0   0   0
y3  0   0   146 0   0   0
y4  0   0   0   0   345 0
y5  0   0   0   109 0   0
y6  0   0   0   0   0   404

and so forth...

Please, is there any elegant solution, how to do that. Any advice or help is very appreciated. Thanks a lot in forward.

Upvotes: 2

Views: 162

Answers (1)

Pafnucy
Pafnucy

Reputation: 628

Create a diagonal matrix and then permute rows or columns. In case of single random permutation sample(n) would suffice, for all of them - allPerms.

n <- 3  # dimension
mat <- diag(1:n)

permute::allPerms(n) -> perms
mat[perms[k, ], ]   # k-th permutation

Downside is that all permutations are generated and saved.

Upvotes: 1

Related Questions