在R中反向下拉三角矩阵的树列表 [英] Tree list to reverse-lower triangular matrix in R

查看:288
本文介绍了在R中反向下拉三角矩阵的树列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何转换

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

to

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

或一些指导意见!感谢您的耐心等待,如果问题太天真,或者需要额外的资料(我会很乐意提供)。

An idea or some guidance are appreciated! Thank you for your patience, in case the question is too naive or requires additional information (I'll gladly provide).

推荐答案

1) lapply 下方向 n > m ,而 sapply 取得$ $ c的每个组件的第一个 n 元素$ c> m 将结果重新形成矩阵。最后我们反转所得到的矩阵的行的顺序。即使 m 没有定义一个三角矩阵,这样也可以工作:

1) Below the lapply appends n zeros to each component of m and the sapply takes the first n elements of each component of m reshaping the result into a matrix. Finally we reverse the order of the rows of the resulting matrix. This works even if m does not define a triangular matrix:

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

If n can be zero then use rev(seq_len(n)) in place of n:1 .

2)一个直接的 sapply 也可以使用。它将每个相反的组件 m 添加到一个矩阵中的适当数量的零和重新形状:

2) A straight forward sapply also works. It prepends each reversed component of m with the appropriate number of zeros and reshapes into a matrix:

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

这篇关于在R中反向下拉三角矩阵的树列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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