r - 在同一函数中调用在 R 中的函数中创建的分配变量
问题描述
我正在编写一个函数来解决数独难题。此函数的一部分将用于将矩阵拆分为三个 9x3 矩阵。然后,在将矩阵重新加入一个大矩阵之前,我将对每个矩阵执行操作。
在这个阶段,我希望我的这部分功能做三件事:
- 将矩阵拆分为三个矩阵
- 命名每个创建的矩阵
- 在同一函数中调用新矩阵
但是,我在第 3 步中苦苦挣扎。我编写了一个函数,将矩阵分成三个,命名每个新矩阵,如果我放入行中envir = globalenv()
,该函数确实返回我的矩阵,分成三个 9x3 矩阵,每个矩阵都有它的个人标识符名称。伟大的!
但是,我想在函数的下一部分中调用函数的第 1 步和第 2 步创建的新矩阵。在运行该函数之前,我不会知道矩阵的名称,因为我希望代码可用于许多矩阵,无论大小如何。
有没有办法在 main 函数中调用由 assign 函数创建的对象,当我只知道对象的名称将是“mat_n”时,n 是一个整数。
为清楚起见,这是我的代码的简化版本:
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 函数创建的对象的特定解决方案,以便在创建它们后在我的 main 函数中使用。这将是一项有用的技能,并且是我编程知识的空白(根本不是很广泛)。
这可能也不是拆分矩阵的最佳方法,而且我知道已经创建了一些包可以解决数独难题,但我想自己写,没有比一开始做不好更好的学习方法然后改进它。
解决方案
使用ls
and怎么样parent.frame
?
mat_4 <- matrix(LETTERS[1:16],nrow=4)
test <- function(){
ls(parent.frame())[grep("mat_",ls(parent.frame()))]
}
test()
# [1] "mat_4"
get(test())
# [,1] [,2] [,3] [,4]
# [1,] "A" "E" "I" "M"
# [2,] "B" "F" "J" "N"
# [3,] "C" "G" "K" "O"
# [4,] "D" "H" "L" "P"
或者,如果您想包含当前环境和更高级别,则有sys.frame()
.
编辑
为了避免必须知道对象的名称,也许将结果存储在列表的元素中是一个更好的计划。
matrix_split <- function(x){
i <- 1:length(x[, 1])
a <- 1:sum(i %% 3 == 0)
b <- which(i %% 3 == 0)
#initialize list
result <- list()
for(n in a){
# assign submatrix to element in the list
result[[n]] <- x[, c((b[a[n]] - (sum(i %% 3 == 0) - 1)) : b[a[n]])]
}
do.call(cbind,result)
}
matrix_split(m)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 6 4 2 9 1 2 8 0 4
[2,] 8 5 5 8 6 1 3 7 8
[3,] 4 7 1 8 3 6 6 0 6
[4,] 3 0 5 0 6 3 2 3 9
[5,] 0 9 7 7 0 1 5 3 2
[6,] 0 8 8 9 9 8 4 9 8
[7,] 6 0 2 9 9 2 4 8 9
[8,] 6 9 6 4 8 1 2 1 1
[9,] 8 4 6 8 5 0 9 5 9
推荐阅读
- isabelle - 什么样的函数保留了闭包的性质?
- javascript - JS - 将字符串值转换为数字、布尔值或字符串的最佳方法?
- c - Cygwin makefile 编译找不到 -lregex
- c# - 未创建使用 smtp 客户端线程的 gmail 重播
- javascript - 如何在不使用 JavaScript 中的减号运算符的情况下减去两个数字?或使用 For 循环
- android - 如何在 kodein 中调用的第二时间重新绑定模块?
- javascript - 当我们编写 for..of 循环时,它如何在内部调用 symbol.iterator
- php - 如何在 php 数组中搜索字符串,但仅在特定键内?
- javascript - vuejs - 获取调用方法的元素
- sql - 我如何从多个表中获得所需的结果,如下所示