R:对行间隔求和 [英] R: summing over an interval of rows

查看:62
本文介绍了R:对行间隔求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 R 初学者,我需要编写一个函数,在固定间隔(每 4 行)内对数据帧的行进行求和.我试过下面的代码

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)
}

结果是X[i:(i + 4), ] 中的错误:索引超出范围".我该如何解决?有什么建议吗?

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

谢谢.

推荐答案

zoo 包有 rollapply ,这对于这样的事情非常方便......

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

如果您确实想将列聚合为 4 行中的每一行的单个值,您也可以对结果使用 rowSums()...

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

这篇关于R:对行间隔求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆