【问题标题】:Tree list to reverse-lower triangular matrix in RR中反向下三角矩阵的树列表
【发布时间】:2016-02-15 16:41:42
【问题描述】:

我将如何进行转换

m = list(1,2:3,4:6,7:10)

     [,1] [,2] [,3] [,4]
[1,]    0    0    0   10
[2,]    0    0    6    9
[3,]    0    3    5    8
[4,]    1    2    4    7

感谢您的想法或一些指导!感谢您的耐心等待,以防问题过于幼稚或需要更多信息(我很乐意提供)。

【问题讨论】:

    标签: r list matrix data-structures tree


    【解决方案1】:

    我会向前推进一个基本的 R 方法

    # Create matrix with dimensions defined by the length of your list 
    mat <- matrix(0, length(m), length(m)) 
    # Fill in desired order
    mat[upper.tri(mat, TRUE)] <- unlist(m)
    # Order rows 
    mat[length(m):1, ]
    

    【讨论】:

    • 因为你的答案要好 100 倍。数字到字符回到数字并不是真正应该做的事情
    • 是的,也许吧,但我确实认为引入隐藏在包中的鲜为人知的功能很有用(否则我永远不会了解它们!)
    【解决方案2】:

    1)lapply 下方将n 零附加到m 的每个组件,sapply 获取m 的每个组件的第一个n 元素结果变成一个矩阵。最后,我们颠倒生成矩阵的行顺序。即使m 没有定义三角矩阵,这仍然有效:

    n <- length(m)
    sapply(lapply(m, c, numeric(n)), head, n)[n:1, ]
    

    给予:

         [,1] [,2] [,3] [,4]
    [1,]    0    0    0   10
    [2,]    0    0    6    9
    [3,]    0    3    5    8
    [4,]    1    2    4    7
    

    如果n 可以为零,则使用rev(seq_len(n)) 代替n:1

    2) 直截了当的sapply 也可以。它在 m 的每个反转组件前面加上适当数量的零,然后重新整形为一个矩阵:

    sapply(m, function(v) c(numeric(n - length(v)), rev(v)))
    

    【讨论】:

      【解决方案3】:

      这是另一个可供考虑的选择。这使用lengths 来计算最长向量的长度,然后使用vapply,它会自动简化为矩阵(类似于sapply,但更快)。

      len <- max(lengths(m))           ## What's the longest vector in m?
      vapply(m, function(x) {
        length(x) <- len               ## Make all vectors the same length
        rev(replace(x, is.na(x), 0))   ## Replace NA with 0 and reverse
      }, numeric(len))
      #      [,1] [,2] [,3] [,4]
      # [1,]    0    0    0   10
      # [2,]    0    0    6    9
      # [3,]    0    3    5    8
      # [4,]    1    2    4    7
      

      【讨论】:

        【解决方案4】:

        如果您使用稀疏矩阵(来自Matrix 包),这些也可以工作:

        > N <- lengths(m)
        > sparseMatrix(i=1+length(m)-sequence(N), j=rep.int(N,N), x=unlist(m))
        4 x 4 sparse Matrix of class "dgCMatrix"
        
        [1,] . . . 10
        [2,] . . 6  9
        [3,] . 3 5  8
        [4,] 1 2 4  7
        

        这和上三角矩阵的成语几乎一样:

        > sparseMatrix(i=sequence(N), j=rep.int(N,N), x=unlist(m))
        4 x 4 sparse Matrix of class "dgCMatrix"
        
        [1,] 1 2 4  7
        [2,] . 3 5  8
        [3,] . . 6  9
        [4,] . . . 10
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-06-17
          • 2017-12-19
          • 1970-01-01
          • 2011-06-16
          • 1970-01-01
          • 1970-01-01
          • 2015-08-27
          • 2014-11-27
          相关资源
          最近更新 更多