R:从字符串名称向量中调用矩阵?

ska*_*kan 0 string r object matrix call

想象一下,我有100个数字矩阵,每个矩阵有5列.我将这些矩阵的名称保存在向量或列表中:

Mat <- c("GON1EU", "GON2EU", "GON3EU", "NEW4", ....)
Run Code Online (Sandbox Code Playgroud)

我还有一个系数向量"coef",

coef <- c(1, 2, 2, 1, ...)
Run Code Online (Sandbox Code Playgroud)

我想以这种方式计算结果向量:

coef[1]*GON1EU[,1]+coef[2]*GON2EU[,1]+coef[3]*GON3EU[,1]+coef[4]*NEW4[,1]+.....
Run Code Online (Sandbox Code Playgroud)

如何使用名称向量以紧凑的方式完成?

就像是:

coef*(Object(Mat)[,1])
Run Code Online (Sandbox Code Playgroud)

我认为关键是如何使用他的名字和使用以及矢量符号从字符串中调用对象.但我不知道怎么做.

Rei*_*son 6

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)
Run Code Online (Sandbox Code Playgroud)

这是一些输出:

> 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
Run Code Online (Sandbox Code Playgroud)

上面的示例建议您从分析的一开始就创建或读入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
Run Code Online (Sandbox Code Playgroud)

"mat"反复使用,Mat因为这是我上面的矩阵的名称.你会用自己的Mat.如果vec包含你所拥有的内容coef,并myList使用for上面的循环创建,那么你需要做的就是:

colSums(sapply(myList, function(x) x[, 1]) * vec)
Run Code Online (Sandbox Code Playgroud)

得到你想要的答案.