r - 将矩阵添加到列表时按名称和维度索引列表元素

标签 r matrix

我正在 for 循环中工作,其中每次迭代都会生成一个矩阵,并希望将结果矩阵存储在列表中。循环的结构方式使得我不能简单地通过循环索引对结果列表进行索引,例如 ResultsList[[i]] <- ResultsMx在这个实例中将不起作用。

相反,我需要添加 ResultsMxResultsList通过匹配名称,但不确定如何索引正确的名称和定义而不出现错误:number of items to replace is not a multiple of replacement length

例如,我想添加这个矩阵

ResultsMx <- structure(c(0.280409, 0.248557, 0.193688, 0.120225, 0.060881, 
                0.03218, 0.029315, 0.019525, 7e-06, 3e-06, 0.306503, 0.240209, 
                0.224629, 0.133996, 0.043117, 0.016981, 0.012545, 0.003268, 7.8e-05, 
                5.8e-05, 0.219001, 0.202018, 0.197539, 0.188427, 0.093204, 0.047265, 
                0.033493, 0.007712, 0.000352, 0.00015, 0.126588, 0.15627, 0.161544, 
                0.194544, 0.171473, 0.103416, 0.070513, 0.014678, 0.001778, 0.000774, 
                0.054797, 0.100531, 0.1249, 0.171576, 0.21895, 0.168987, 0.120546, 
                0.045224, 0.006602, 0.003019, 0.012318, 0.045509, 0.073426, 0.125358, 
                0.225135, 0.219425, 0.169645, 0.117345, 0.030413, 0.011488, 0.000385, 
                0.006894, 0.023663, 0.060295, 0.151452, 0.242802, 0.222163, 0.206509, 
                0.098567, 0.04849, 0, 1.2e-05, 0.000611, 0.005577, 0.035691, 
                0.151408, 0.239021, 0.301288, 0.230251, 0.211833, 0, 0, 0, 2e-06, 
                9.8e-05, 0.017526, 0.098463, 0.245786, 0.417003, 0.724185, 0, 
                0, 0, 0, 0, 9e-06, 0.004297, 0.038665, 0.21495, 0), .Dim = c(10L, 
                                                                             10L))

到这个空白矩阵列表:

SeasonResults <- list(BHSSummSymScReClass = matrix(0, nrow = 10, ncol = 10),
                      MTGSummSymScReClass = matrix(0, nrow = 10, ncol = 10),
                      BHSWintSymScReClass = matrix(0, nrow = 10, ncol = 10),
                      MTGWintSymScReClass = matrix(0, nrow = 10, ncol = 10)) 

通过将列表元素与该名称对象进行匹配:

SeasonNames <- c("BHSSummSymScReClass", "MTGSummSymScReClass")

这里使用以下代码将第一个列表项与第一个 SeasonName 进行匹配项目:

SeasonResults[names(SeasonResults) == SeasonNames[1]] <- ResultsMx

它会生成上述警告,并且仅添加 ResultsMx 中的 1,1 元素.

如何指定正确的尺寸,以便整个 ResultsMx添加到 SeasonResults基于与 SeasonNames 匹配的名称的列表?

我看过很多相关的 SO 帖子,但没有一个能满足我根据名称匹配和维度进行索引的需要。

提前致谢。

最佳答案

我们可以将 for 循环与 which 函数一起使用。 which 寻找 其中 names(SeasonResults)SeasonNames 中找到的内容匹配。然后我们迭代这些索引,用 ResultsMx 替换内容。

for(i in which(names(SeasonResults) %in% SeasonNames)){
    SeasonResults[[i]] <- ResultsMx
}

关于r - 将矩阵添加到列表时按名称和维度索引列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45635351/

相关文章:

r - deparse(substitute()) 正常返回函数名,但在 for 循环内部调用时返回函数代码

r - 按特定(自定义)顺序对整数向量进行排序

r - R 中的子矩阵采样

python - 在同一个图上一起绘制两个距离矩阵?

c - 为什么这个矩阵加法代码给出了错误的答案?

search - 在排序矩阵(mXn)中查找特定值,时间复杂度为 O(lgm) + O(lgn)

r - 在 dplyr 中使用 group_by 时如何获得总体统计数据?

linux - R包中的依赖错误

mysql - R Shiny 中的selectInput

来自多个文件的 Python txt 矩阵