List of trees for the inverse triangular matrix in R

How do I switch to conversion

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 appreciated! Thank you for your patience if the question is too naive or requires additional information (I gladly provided).

+5
source share
4 answers

1) Below lapply adds zeros n to each component m , and sapply takes the first elements n each component m , changing the shape of the result into a matrix. Finally, we reverse the row order 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 null, use rev(seq_len(n)) instead of n:1 .

2) Direct sapply also works. It adds each inverse component m with the corresponding number of zeros and converts it into a matrix:

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

Turn the basic method R 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, ] 
+7
source

Here is another option to consider. This uses lengths to figure out how long the vector is, and then uses vapply , which automatically simplifies the matrix (e.g. sapply , but faster).

 len <- max(lengths(m)) ## What 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 
+1
source

If you use sparse matrices (from the Matrix package), they will also work:

 > 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 

This is almost the same as the idiom for the upper triangular matrices:

 > 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 
+1
source

Source: https://habr.com/ru/post/1235937/


All Articles