0

I'm a beginner R user and I need to write a function that sums the rows of a data frame over a fixed interval (every 4 rows). I've tried the following code

camp<-function(X){
  i<-1
  n<-nrow(X)
  xc<-matrix(nrow=36,ncol=m)
  for (i in 1:n){
    xc<-apply(X[i:(i+4),],2,sum)
    rownames(xc[i])<-rownames(X[i])
    i<-i+5
  }
  return(xc)
}

the result is "Error in X[i:(i + 4), ] : index out of range". How can I solve? Any suggestion?

Thanks.

digEmAll
  • 56,430
  • 9
  • 115
  • 140
Ndr
  • 550
  • 3
  • 15
  • Please provide [a reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) explaining what's your desired result... – digEmAll Oct 26 '13 at 13:41

2 Answers2

2

The zoo package has rollapply which is pretty handy for stuff like this...

#  Make some data
set.seed(1)
m <- matrix( sample( 10 , 32 , repl = TRUE ) , 8 )
#     [,1] [,2] [,3] [,4]
#[1,]    3    7    8    3
#[2,]    4    1   10    4
#[3,]    6    3    4    1
#[4,]   10    2    8    4
#[5,]    3    7   10    9
#[6,]    9    4    3    4
#[7,]   10    8    7    5
#[8,]    7    5    2    6

#  Sum every 4 rows
require( zoo )
tmp <- rollapply( m , width = 4 , by = 4 , align = "left" , FUN = sum )
#     [,1] [,2] [,3] [,4]
#[1,]   23   13   30   12
#[2,]   29   24   22   24

You can also use rowSums() on the result if you actually wanted to aggregate the columns into a single value for each of the 4 rows...

rowSums( tmp )
#[1] 78 99
Simon O'Hanlon
  • 58,647
  • 14
  • 142
  • 184
1

Here is a way to do it :

## Sample data
m <- matrix(1:36, nrow=12)
## Create a "group" index
fac <- (seq_len(nrow(m))-1) %/% 4
## Apply sum 
apply(m, 2, function(v) tapply(v, fac, sum))

Sample data :

      [,1] [,2] [,3]
 [1,]    1   13   25
 [2,]    2   14   26
 [3,]    3   15   27
 [4,]    4   16   28
 [5,]    5   17   29
 [6,]    6   18   30
 [7,]    7   19   31
 [8,]    8   20   32
 [9,]    9   21   33
[10,]   10   22   34
[11,]   11   23   35
[12,]   12   24   36

Result :

  [,1] [,2] [,3]
0   10   58  106
1   26   74  122
2   42   90  138
juba
  • 47,631
  • 14
  • 113
  • 118