(我会先在聊天中询问,但我的业力不够。)
我有包含矩阵的列表,例如:
List1 <- list(ch1 = matrix(1:4, ncol = 2), ch2 = matrix(5:8, ncol = 2))
List2 <- list(ch1 = matrix(2:5, ncol = 2), ch2 = matrix(6:9, ncol = 2))
我现在想要对环境中的所有列表执行计算,并将结果作为另一个矩阵附加到相应列表中。假设 ch3 应该是 ch1 + ch2,所以 List1 看起来像:
$ch1
[,1] [,2]
[1,] 1 3
[2,] 2 4
$ch2
[,1] [,2]
[1,] 5 7
[2,] 6 8
$ch3
[,1] [,2]
[1,] 6 10
[2,] 8 12
由于列表的长度不同,我必须按名称、ch1 等对矩阵进行寻址。
我的方法得到了正确的结果,但不是作为矩阵附加,而是作为整数附加。解决这个问题很麻烦,所以肯定有更好的方法。
LST <- objects(pattern = "List+(\\d+)", envir = globalenv())
for (i in 1:length(LST)){
pointer1 <- which(names(get(LST[[i]])) == "ch1")
pointer2 <- which(names(get(LST[[i]])) == "ch2")
matrix1 <- get(LST[[i]])[pointer1][[1]]
matrix2 <- get(LST[[i]])[pointer2][[1]]
result <- matrix1 + matrix2
# print(dim(result))# results in 2 2, as expected
assign(LST[[i]], c(get(LST[[i]]), matrix(result, ncol = ncol(matrix1))))
# rm(pointer1, pointer2, matrix1, matrix2, result)
}
作为我的每个大约。 100 个列表由超过 15 个矩阵组成,每个矩阵最多 300MB,由于内存限制,我无法将它们合并到数组中。理想情况下,我最终会得到一个函数或像 lapply 这样简洁的东西,但是,我无法让它们正常工作。
最佳答案
我已经解决了。必须以比预期更多的步骤进行编码,由于某种原因它只能像这样工作。考虑以下因素:
List1 <- list(ch1 = matrix(1:4, ncol = 2), ch2 = matrix(5:8, ncol = 2))
List2 <- list(ch1 = matrix(2:5, ncol = 2), ch2 = matrix(6:9, ncol = 2))
LST <- objects(pattern = "List+(\\d+)", envir = globalenv())
for (i in 1:length(LST)){
pointer1 <- which(names(get(LST[[i]])) == "ch1")
pointer2 <- which(names(get(LST[[i]])) == "ch2")
matrix1 <- get(LST[[i]])[pointer1][[1]]
matrix2 <- get(LST[[i]])[pointer2][[1]]
result <- matrix1 + matrix2
tmpList <- get(LST[[i]])
ListLength <- length(tmpList)
chNames <- names(tmpList)
chNames <- c(chNames, "ch3")
tmpList[[ListLength + 1]] <- result
names(tmpList) <- chNames
assign(LST[[i]], tmpList)
}
rm(i, ListLength, LST, pointer1, pointer2, matrix1, matrix2, result, chNames, tmpList)
产生期望的结果:
> List1
$ch1
[,1] [,2]
[1,] 1 3
[2,] 2 4
$ch2
[,1] [,2]
[1,] 5 7
[2,] 6 8
$ch3
[,1] [,2]
[1,] 6 10
[2,] 8 12
> List2
$ch1
[,1] [,2]
[1,] 2 4
[2,] 3 5
$ch2
[,1] [,2]
[1,] 6 8
[2,] 7 9
$ch3
[,1] [,2]
[1,] 8 12
[2,] 10 14
关于R:将结果矩阵附加到环境中的所有列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46348147/