Given a vector I would like to create a square matrix where elements of vector are on diagonal and there is row-wise cumsum of elements.
Example vector:
vec <- c(1, 2, 3, 4)
Required output:
[,1] [,2] [,3] [,4]
[1,] 1 3 6 10
[2,] 0 2 5 9
[3,] 0 0 3 7
[4,] 0 0 0 4
Now, I am using double for loop function:
diagSum <- function(vec) {
mat <- diag(vec)
for (i in seq(nrow(mat))) {
for (j in seq(i, ncol(mat))) {
if (j > i) {
mat[i, j] <- mat[i, j - 1] + mat[j, j]
}
}
}
mat
}
What would be R-way (avoiding for loops) of doing this?