gpt4 book ai didi

r - 将列表中多个矩阵的上三角复制到下三角

转载 作者:行者123 更新时间:2023-12-04 03:04:04 29 4
gpt4 key购买 nike

我想将上三角复制到存储在列表中的一堆矩阵的下三角。

创建一个矩阵列表,上面的三角形只填充了数据:

m1<-matrix(1:9, 3, 3);lower.tri(m1);m1[lower.tri(m1)]<- NA; m1
m2<-matrix(9:18, 3, 3);lower.tri(m2);m2[lower.tri(m2)]<- NA; m2
m3<-matrix(18:27, 3, 3);lower.tri(m3);m3[lower.tri(m3)]<- NA; m3
m4<-matrix(27:36, 3, 3);lower.tri(m4);m4[lower.tri(m4)]<- NA; m4

L<-list(m1,m2, m3, m4); L

要将上三角复制到矩阵的下三角,您可以使用:
M <- m1
for(i in 1:nrow(M)) {for(j in 1:i) {M[i,j]=M[j,i] }}
M

但是,我想将列表“L”中的每个矩阵的上三角复制到下三角

最佳答案

处理此类任务的典型策略是首先创建一个函数,该函数对单个列表元素(此处为单个上三角矩阵)执行您想要的操作,然后使用 lapply()依次将其应用于每个列表元素。

在这种情况下,这是我将使用的:

f <- function(m) {
m[lower.tri(m)] <- t(m)[lower.tri(m)]
m
}

## Check that it works on a single list element
f(L[[1]])
# [,1] [,2] [,3]
# [1,] 1 4 7
# [2,] 4 5 8
# [3,] 7 8 9

## Use lapply() to apply it to each list element
lapply(L, f)
# [[1]]
# [,1] [,2] [,3]
# [1,] 1 4 7
# [2,] 4 5 8
# [3,] 7 8 9
#
# [[2]]
# [,1] [,2] [,3]
# [1,] 9 12 15
# [2,] 12 13 16
# [3,] 15 16 17
#
# [[3]]
# [,1] [,2] [,3]
# [1,] 18 21 24
# [2,] 21 22 25
# [3,] 24 25 26
#
# [[4]]
# [,1] [,2] [,3]
# [1,] 27 30 33
# [2,] 30 31 34
# [3,] 33 34 35

关于r - 将列表中多个矩阵的上三角复制到下三角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26166569/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com