Hello,

I'd like to take all possible sub-summands of a vector in the quickest and
most efficient way possible.  By "sub-summands" I mean for each sub-vector,
take its sum.  Which is to say: if I had the vector

x<-1:4

I'd want the "sum" of x[1], x[2], etc.  And then the sum of x[1:2], x[2:3],
etc.  And then...so on.

The result would be:
1 2 3 4
2 5 7
6 9
10

I can do this with for loops (code below) but for long vectors (10^6
elements) looping takes more time than I'd like.  Any suggestions?

Thanks very much in advance--
Andy


# calculate sums of all sub-vectors...
x <- 1:4

sub.vect <- vector("list",4)

for(t in 1:4) {
    maxi <- 4 - t + 1
    this.sub <- numeric(maxi)
    for(i in 1:maxi) {
        this.sub[i] <- sum(x[i:(i+t-1)])
    }
    sub.vect[[t]] <- this.sub
}

sub.vect

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to