r-当矩阵可以有可变行数时,我想从矩阵的每一行扩展.grid

  • 本文关键字:一行 grid 扩展 matrix combinations
  • 更新时间 :
  • 英文 :


myMatrix <- matrix(c(1,2,3,4,5,6),2,3, byrow=T) # line 1
exp.myMatrix <- function(myMatrix) { # line 2
  for (rownum in 1:nrow(myMatrix)) assign(paste("R",rownum, sep=""), myMatrix[rownum,]) # line 3
  Combinations <- do.call(expand.grid, lapply(ls(pattern='^R\d$'), get)) # line 4
  rm(list=ls(pattern='^R\d$')) # line 5
  return(Combinations) # line 6
} # line 7
Combinations <- exp.myMatrix(myMatrix) # line 8

上面的代码给出了错误:"FUN(X[[i]],…(中的错误:找不到对象'R1'"。

然而,当我不使用该函数,只运行第1、3、4、5行时,我不会得到任何错误。但我需要通过一个函数传递myMatrix,因为矩阵的行数是可变的。还要注意,我需要运行第5行,因为我需要清除下一个矩阵的变量,该矩阵的行数可能比上一个矩阵少。

您必须使用:

do.call(expand.grid, split(myMatrix, rep(1:nrow(myMatrix), ncol(myMatrix))))
#  1 2
#1 1 4
#2 2 4
#3 3 4
#4 1 5
#5 2 5
#6 3 5
#7 1 6
#8 2 6
#9 3 6