简体   繁体   中英

all distinct combinations of N=50 and K=3

How do I create a matrix in R with 50 individuals having labels K=1,2,3 and then all possible outcomes? It does not seem to be either combinations or per muations. So as an example with N=2 the following, only then not 2 rows but 50. So I get a 50x3^50 matrix.

> cbind(c(1,1),c(1,2),c(1,3),c(2,1),c(2,2),c(2,3),c(3,1),c(3,2),c(3,3))
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,]    1    1    1    2    2    2    3    3    3
[2,]    1    2    3    1    2    3    1    2    3

And for N=3:

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24] [,25] [,26] [,27]
[1,]    1    1    1    1    1    1    1    1    1     2     2     2     2     2     2     2     2     2     3     3     3     3     3     3     3     3     3
[2,]    1    1    1    2    2    2    3    3    3     1     1     1     2     2     2     3     3     3     1     1     1     2     2     2     3     3     3
[3,]    1    2    3    1    2    3    1    2    3     1     2     3     1     2     3     1     2     3     1     2     3     1     2     3     1     2     3

This gets you partway there but I think there might be a practical problem with your definition. What it sounds like you want is impractical for N=50.

f <- function(n, K) {
    (replicate(n, 1:K, simplify = FALSE)  ## n copies of 1:K
        |> do.call(what = expand.grid)    ## pass these all to expand.grid
        |> as.matrix()                    ## convert to matrix
        |> t()                            ## transpose
    )
}

f(2) and f(3) look like your examples above. However ...

  • f(2) is 2 x 9 (ie, 2 by K^2)
  • f(3) is 3 x 27 (3 by K^3)
  • f(4) is 4 x 81 (3 by K^4)

... so if we continue on this way, the results for N=50 will not be 50 x 50^2 but N x K^N = 50 x 3^50, which is 3.5 x 10^25 ...

... so you might need to rethink something about your strategy. (50^3 would be OK, but 3^50 is not!)

You can try the code below for code-golfing if you like

k <- 3
n <- 4
t(expand.grid(rep(list(1:k), n)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM