该zoo
软件包rollapply
对于应用这样的滚动功能非常有用。您可以使用sapply
循环 a 的列data.frame
并应用rollapply
函数(sapply
循环列表的元素,数据框实际上是列表的集合)。
希望这个例子有意义......
require(zoo)
## Sample data, two columns one million rows
df <- data.frame( A = runif(1e6) , B = runif(1e6) )
## Set desried 'chunk' size, i.e. the
## number of rows to find the mean of
## at once. Let's do 1e4, so we will
## get 100 values back (1e6/1e4=1e2)
m = 1e4
## use sapply to loop across the columns, and
## apply rollapply to each column, which takes
## the mean of each set of 10,000 values
dfMean <- sapply( df , function(x) rollapply( x , width = m , by = m , align = "left" , FUN = mean ) )
nrow(dfMean)
#[1] 100
head(dfMean)
# A B
#[1,] 0.4966775 0.4992207
#[2,] 0.5013934 0.4986489
#[3,] 0.4994544 0.5009876
#[4,] 0.5020374 0.4979467
#[5,] 0.5049408 0.4999280
#[6,] 0.4969987 0.5018564