From: Marc Schwartz <marc_schwartz_at_comcast.net>

Date: Wed, 23 Jul 2008 10:36:31 -0500

R-help_at_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. Received on Wed 23 Jul 2008 - 16:35:34 GMT

Date: Wed, 23 Jul 2008 10:36:31 -0500

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

R-help_at_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. Received on Wed 23 Jul 2008 - 16:35:34 GMT

Archive maintained by Robert King, hosted by
the discipline of
statistics at the
University of Newcastle,
Australia.

Archive generated by hypermail 2.2.0, at Wed 23 Jul 2008 - 17:32:25 GMT.

*
Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help.
Please read the posting
guide before posting to the list.
*