将列表中的多个矩阵的上三角形复制到下三角形 [英] Copy upper triangle to lower triangle for several matrices in a list

查看:156
本文介绍了将列表中的多个矩阵的上三角形复制到下三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to copy the upper triangle to the lower triangle of a bunch of matrices stored in a list.

创建一个矩阵列表,其中只有上三角填充数据:

Create a list of matrices with only the upper triangle filled with data:

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

要将矩阵的上三角复制到下三角,可以使用:

To copy the upper triangle to the lower triangle of the matrix you can use:

M <- m1
for(i in 1:nrow(M)) {for(j in 1:i) {M[i,j]=M[j,i] }}
M

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

However, I want to copy the upper triangle to the lower for each of matrix in the list "L"

推荐答案

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

A typical strategy for tasks like this is to first work up a function that does what you'd like to a single list element (here a single upper-triangular matrix), and then use lapply() to apply it in turn to each of the list elements.

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

In this case, here's what I'd use:

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

这篇关于将列表中的多个矩阵的上三角形复制到下三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆