get() 允许您通过字符串引用对象。不过,它只会让你走这么远;您仍然需要在列表矩阵等上构造对 get() 的重复调用。但是,我想知道替代方法是否可行?为什么不将矩阵单独存储在工作区中,而不是将矩阵存储在列表中?
然后你可以使用列表上的sapply() 来提取列表中每个矩阵的第一列。 sapply() 步骤返回一个矩阵,我们将其乘以系数向量。该矩阵的列总和是您从上述描述中看起来想要的值。至少我假设coef[1]*GON1EU[,1] 是length(GON1EU[,1]) 等的向量。
这里有一些实现这个想法的代码。
vec <- 1:4 ## don't use coef - there is a function with that name
mat <- matrix(1:12, ncol = 3)
myList <- list(mat1 = mat, mat2 = mat, mat3 = mat, mat4 = mat)
colSums(sapply(myList, function(x) x[, 1]) * vec)
这是一些输出:
> sapply(myList, function(x) x[, 1]) * vec
mat1 mat2 mat3 mat4
[1,] 1 1 1 1
[2,] 4 4 4 4
[3,] 9 9 9 9
[4,] 16 16 16 16
> colSums(sapply(myList, function(x) x[, 1]) * vec)
mat1 mat2 mat3 mat4
30 30 30 30
以上示例建议您从分析一开始就创建或读入 100 个矩阵作为列表的组成部分。这将要求您更改用于生成 100 个矩阵的代码。鉴于您的工作区中已经有 100 个矩阵,要从这些矩阵中获取 myList,我们可以使用您已有的名称向量并使用循环:
Mat <- c("mat","mat","mat","mat")
## loop
for(i in seq_along(myList2)) {
myList[[i]] <- get(Mat[i])
}
## or as lapply call - Kudos to Ritchie Cotton for pointing that one out!
## myList <- lapply(Mat, get)
myList <- setNames(myList, paste(Mat, 1:4, sep = ""))
## You only need:
myList <- setNames(myList, Mat)
## as you have the proper names of the matrices
我在Mat 中反复使用"mat",因为这是我上面矩阵的名称。您将使用自己的Mat。如果vec 包含您在coef 中的内容,并且您使用上面的for 循环创建myList,那么您需要做的就是:
colSums(sapply(myList, function(x) x[, 1]) * vec)
为了得到你想要的答案。