I have a number vector as below.
c <- c(5, 4.5, 4, 3.5, 3, 2.5, 2, 1.5, 1, 0.5, 0, 0)
Is there an efficient I can create a matrix or data.table like below? I thought of doing a loop but it takes a long time because the real dataset is large.
5 4.5 4 3.5 3 2.5 2 1.5 1 0.5 0 0
0 5 4.5 4 3.5 3 2.5 2 1.5 1 0.5 0
0 0 5 4.5 4 3.5 3 2.5 2 1.5 1 0.5
0 0 0 5 4.5 4 3.5 3 2.5 2 1.5 1
0 0 0 0 5 4.5 4 3.5 3 2.5 2 1.5
0 0 0 0 0 5 4.5 4 3.5 3 2.5 2
0 0 0 0 0 0 5 4.5 4 3.5 3 2.5
0 0 0 0 0 0 0 5 4.5 4 3.5 3
0 0 0 0 0 0 0 0 5 4.5 4 3.5
0 0 0 0 0 0 0 0 0 5 4.5 4
0 0 0 0 0 0 0 0 0 0 5 4.5
0 0 0 0 0 0 0 0 0 0 0 5
Any idea is appreciated!
CodePudding user response:
We could use toeplitz
out <- toeplitz(c)
out[lower.tri(out)] <- 0
-output
> out
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,] 5 4.5 4.0 3.5 3.0 2.5 2.0 1.5 1.0 0.5 0.0 0.0
[2,] 0 5.0 4.5 4.0 3.5 3.0 2.5 2.0 1.5 1.0 0.5 0.0
[3,] 0 0.0 5.0 4.5 4.0 3.5 3.0 2.5 2.0 1.5 1.0 0.5
[4,] 0 0.0 0.0 5.0 4.5 4.0 3.5 3.0 2.5 2.0 1.5 1.0
[5,] 0 0.0 0.0 0.0 5.0 4.5 4.0 3.5 3.0 2.5 2.0 1.5
[6,] 0 0.0 0.0 0.0 0.0 5.0 4.5 4.0 3.5 3.0 2.5 2.0
[7,] 0 0.0 0.0 0.0 0.0 0.0 5.0 4.5 4.0 3.5 3.0 2.5
[8,] 0 0.0 0.0 0.0 0.0 0.0 0.0 5.0 4.5 4.0 3.5 3.0
[9,] 0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 5.0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