# Summing over specific columns in a matrix

5 messages
Open this post in threaded view
|

## Summing over specific columns in a matrix

 Hi, I would like to sum some specific columns in my matrix- for example, my matrix looks like this:      [,1]  [,2]  [,3] [,4]  [,5] [1,]    1   NA   NA   NA   NA [2,]    2    1   NA    1   NA [3,]    3    2    1     2    1 [4,]    4    3    2     3    2 [5,]   NA   NA   NA    4    3 [6,]   NA   NA   NA    5   NA I would like to find the sum of the first two columns, the second two columns and the last column: i.e I am left with a vector of c(16, 18, 6). I know about colSums and sum overall- I just wondered if this type of grouping can be included somehow in a vector such as c(2,2,1)? I don't really want to have to use a loop for this. Many thanks Emma
Open this post in threaded view
|

## Re: Summing over specific columns in a matrix

 Try this: rowSums(rowsum(t(m), rep(1:3, c(2, 2, 1)), na.rm = TRUE)) On Fri, Jan 7, 2011 at 2:29 PM, emj83 <[hidden email]> wrote: > > Hi, > > I would like to sum some specific columns in my matrix- for example, my > matrix looks like this: >     [,1]  [,2]  [,3] [,4]  [,5] > [1,]    1   NA   NA   NA   NA > [2,]    2    1   NA    1   NA > [3,]    3    2    1     2    1 > [4,]    4    3    2     3    2 > [5,]   NA   NA   NA    4    3 > [6,]   NA   NA   NA    5   NA > > I would like to find the sum of the first two columns, the second two > columns and the last column: > i.e I am left with a vector of c(16, 18, 6). > > I know about colSums and sum overall- I just wondered if this type of > grouping can be included somehow in a vector such as c(2,2,1)? I don't > really want to have to use a loop for this. > > Many thanks Emma > -- > View this message in context: > http://r.789695.n4.nabble.com/Summing-over-specific-columns-in-a-matrix-tp3179400p3179400.html> Sent from the R help mailing list archive at Nabble.com. > > ______________________________________________ > [hidden email] 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. > -- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O         [[alternative HTML version deleted]] ______________________________________________ [hidden email] mailing list https://stat.ethz.ch/mailman/listinfo/r-helpPLEASE do read the posting guide http://www.R-project.org/posting-guide.htmland provide commented, minimal, self-contained, reproducible code.
Open this post in threaded view
|

## Re: Summing over specific columns in a matrix

 Thanks- this works just as I needed- Emma