Copy upper triangle to lower triangle for several matrices in a list

前端 未结 1 1940
我在风中等你
我在风中等你 2020-12-09 19:45

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 d

相关标签:
1条回答
  • 2020-12-09 20:18

    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
    
    0 讨论(0)
提交回复
热议问题