[R] sequential sum of a vector...
Marc Schwartz
marc_schwartz at comcast.net
Wed Jul 23 17:36:31 CEST 2008
on 07/23/2008 09:03 AM Shubha Vishwanath Karanth wrote:
> Hi R,
>
>
>
> Let,
>
>
>
> x=1:80
>
>
>
> I want to sum up first 8 elements of x, then again next 8 elements of x,
> then again another 8 elements..... So, my new vector should look like:
>
> c(36,100,164,228,292,356,420,484,548,612)
>
>
>
> I used:
>
>
>
> aggregate(x,list(rep(1:10,each=8)),sum)[-1]
>
> or
>
> rowsum(x,group=rep(1:10,each=8))
>
>
>
>
>
> But without grouping, can I achieve the required? Any other ways of
> doing this?
>
>
>
> Thanks, Shubha
x <- 1:80
> colSums(matrix(x, ncol = 10))
[1] 36 100 164 228 292 356 420 484 548 612
If the original vector 'x' can be coerced to a rectangular matrix, you
can create the matrix such that each column is a group:
> matrix(x, ncol = 10)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 9 17 25 33 41 49 57 65 73
[2,] 2 10 18 26 34 42 50 58 66 74
[3,] 3 11 19 27 35 43 51 59 67 75
[4,] 4 12 20 28 36 44 52 60 68 76
[5,] 5 13 21 29 37 45 53 61 69 77
[6,] 6 14 22 30 38 46 54 62 70 78
[7,] 7 15 23 31 39 47 55 63 71 79
[8,] 8 16 24 32 40 48 56 64 72 80
Then just get the sums of each column. Note that by default, the matrix
is formed by columns. This can be adjusted using the 'byrow' argument to
matrix(). See ?matrix
HTH,
Marc Schwartz
More information about the R-help
mailing list