2015-01-27 11 views
6

Gegeben ein Vektor möchte ich eine quadratische Matrix erstellen, wo Elemente des Vektors auf Diagonale sind und es Reihe-weise Cumsum von Elementen gibt.Berechnen reihenweise Matrix Cumsum aus Vektor

Beispiel Vektor:

vec <- c(1, 2, 3, 4) 

Erforderliche Ausgabe:

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

Nun, ich bin mit Doppel für Loop-Funktion:

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 
} 

Was wäre R-Weg (Vermeidung von für Schleifen), dies zu tun?

Antwort

8
m <- matrix(vec, nrow = length(vec), ncol = length(vec), byrow =TRUE) 
m[lower.tri(m)] <- 0 
t(apply(m, 1, cumsum)) 
#  [,1] [,2] [,3] [,4] 
#[1,] 1 3 6 10 
#[2,] 0 2 5 9 
#[3,] 0 0 3 7 
#[4,] 0 0 0 4 
+0

Ha, Sie schneller mit lower.tri Lösung sind :) –

4

Eine Möglichkeit, dies zu tun:

x <- c(1, 2, 3, 4) 
rbind(cumsum(x), t(sapply(1:3, function(y) c(rep(0, y), cumsum(x[-(1:y)]))))) 
#  [,1] [,2] [,3] [,4] 
# [1,] 1 3 6 10 
# [2,] 0 2 5 9 
# [3,] 0 0 3 7 
# [4,] 0 0 0 4 
4

So:

> x=c(1, 2, 3, 4) 

> do.call(rbind, lapply(1:length(x)-1, function(u) {x[0:u]=0;cumsum(x)})) 
#  [,1] [,2] [,3] [,4] 
#[1,] 1 3 6 10 
#[2,] 0 2 5 9 
#[3,] 0 0 3 7 
#[4,] 0 0 0 4 
Verwandte Themen