我已经被警告过,这个问题与过去曾被否决的问题相似,但是这里有。被动侵略就像鸭子从我的背上流下来。
我正在编写一个函数来解决我在隔离区时遇到的数独难题。此功能的一部分将用于将矩阵分成三个9x3矩阵。然后,我将对每个矩阵执行操作,然后再将矩阵重新合并为一个大矩阵。
在此阶段,我希望函数的这一部分做三件事:
但是,我在第3步中苦苦挣扎。我编写了一个函数,将矩阵拆分为三个,为每个新矩阵命名,如果我在行envir = globalenv()
中输入,该函数的确会将矩阵拆分为三个,即9x3矩阵,每个矩阵都有自己的标识符名称。太好了!
但是,我想在函数的下一部分中调用由函数的步骤1和2创建的新矩阵。在运行函数之前,我将不知道矩阵的名称,因为我希望代码无论大小如何都可用于许多矩阵。
[当我只知道对象的名称将为“ mat_n”,且n为整数时,是否可以在主函数内调用由assign函数创建的对象。
为清楚起见,这是我的代码的简化版本:
m <- matrix(sample(c(0:9), 81, replace = T), ncol = 9, nrow = 9)
matrix_split <- function(x){
i <- 1:length(x[, 1])
a <- 1:sum(i %% 3 == 0) # Will be used to name the temporary matrices
b <- which(i %% 3 == 0) # Will be used to identify where to split main matrix
for(n in a){ # This is to create a number of smaller matrices depending on the
# number multiples of 3 that are present in the length of the object.
nam <- paste("mat_", n, sep = "") # Each new matrix will be named and numbered
# using the assign function below:
assign(nam, x[, c((b[a[n]] - (sum(i %% 3 == 0) - 1)) : b[a[n]])])
# Not a very elegant way of using the loop to split the matrix into blocks of
# three. b[a[n]] returns either 3, 6 or 9, and (sum(i %% == 3) -1 ) = 2. So this
# will return x[, c(1:3)], x[, c(4:6)] and x[, c(7:9)], when spliting the matrix
# into three.
}
}
matrix_split(m)
我只要求特定的解决方案来调用由assign函数创建的对象,这些对象在创建后将在我的主函数中使用。这将是一项有用的技能,并且是我的编程知识上的空白(根本不是很广泛)。
这可能也不是拆分矩阵的最佳方法,而且我知道已经创建了可以解决数独问题的软件包,但是我想编写自己的软件包,没有比做坏事更好的学习方法了首先,然后对其进行改进。
如果以前已经回答过,我还没有找到。这不是由于缺乏尝试,我只是不知道要搜索什么。并非每个人都有编码员或统计学家的词汇。
很多爱,并保持电晕的安全。
如何使用ls
和parent.frame
?
mat_15 <- matrix()
test <- function(){
ls(parent.frame())[grep("mat_",ls(parent.frame()))]
}
test()
[1] "mat_15"