Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tree list to reverse-lower triangular matrix in R

How would I go about converting

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).

like image 855
Oleg Melnikov Avatar asked Nov 14 '15 00:11

Oleg Melnikov


2 Answers

Ill chuck a base R method forward

# 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, ]
like image 114
user20650 Avatar answered Oct 21 '22 06:10

user20650


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, ]

giving:

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

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

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)))
like image 34
G. Grothendieck Avatar answered Oct 21 '22 06:10

G. Grothendieck