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).
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, ]
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With