簡體   English   中英

將 24 X 24 矩陣拆分為 5 X 5 矩陣以獲得 R 中所有可能的行和列組合

[英]Split a 24 X 24 matrix in 5 X 5 matrixes to get all possible combinations of rows and collumns in R

我需要將 24 X 24 dataframe 拆分為 5 X 5 數據幀,其中包括原始 24 X 24 dataframe 中所有可能的行和列組合。 有人來接任務嗎?

有 24 列 5 x 5 的 42504 種組合。乘以相同數量的 24 行 5 x 5 組合,即 1806590016 個矩陣。 每個有 5*5 個元素。 如果它們是 class “整數”(32 位),則需要 168.2518 GB 來存儲結果。

choose(24, 5)^2 * 5^2 * 4 / 1024/1024/1024
#[1] 168.2518

如果確實需要這樣做,這里有一個 function 來創建子數據幀或子矩陣,其中包括原始數據幀或矩陣中所有可能的行和列組合。

sub_df <- function(x, n, output = c("data.frame", "matrix")){
  nr <- nrow(x)
  nc <- ncol(x)
  out <- match.arg(output)
  if(nr != nc){
    warn <- sprintf("the data does not have an equal numbers of rows (%d) and columns (%d)", nr, nc)
    warning(warn)
  }
  if(out == "matrix"){
    combn(nr, n, \(i){
      combn(nc, n, \(j) x[i, j])
    })
  } else {
    combn(nr, n, \(i){
      combn(nc, n, \(j) as.data.frame(x[i, j]), simplify = FALSE)
    }, simplify = FALSE)
  }
}

m <- matrix(1:25, nrow = 5)
sub_df(m, 2)
sub_df(m[-1,], 2)        # gives a warning
sub_df(m, 2, "matrix")
sub_df(m, 2, "list")     # gives an error

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM