如何在多列数据表上滚动 [英] How to rollapply over a multi column data table

查看:95
本文介绍了如何在多列数据表上滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在多列数据表上使用rollapply函数,也就是说,我希望能够独立使用每一列,例如让我们考虑以下datable:

I would like to use the rollapply function over a multi column datatable, namely I would like to be able to use each column independantly for instance let's consider the following datable :

> DT = data.table(x=rep(c("a","b","c"),each=3), y=c(1,3,6), v=1:9)
> DT
   x y v
1: a 1 1
2: a 3 2
3: a 6 3
4: b 1 4
5: b 3 5
6: b 6 6
7: c 1 7
8: c 3 8
9: c 6 9

然后,我想使用rollapply作为滚动子集,以便计算第2列和第3列的3个元素的滚动平均值并将其存储到外部变量中:

Then I would like to use rollapply as a rolling subset in order to work out the rolling mean over 3 element of columns 2 and 3 and store them into external variables :

> r1= NA; r2 = NA
> ft=function(x) { r1=mean(x[,2,with=FALSE]) ; r2=mean(x[,3,with=FALSE]) }
> rollapply(DT, width=3, ft)
 Error in x[, 2, with = FALSE] : incorrect number of dimensions 

除了我得到的这个不方便的错误之外,为什么它不起作用?

Except I got this error which isn't handy, why isn't it working ?

输出为:

> r1
[1] 3.333333 3.333333 3.333333 3.333333 3.333333 3.333333 3.333333
> r2
[1] 2 3 4 5 6 7 8

推荐答案

您快到了并且可以:

lapply(DT[,2:3], function(x) rollapply(x,width=3, FUN=mean))
#$y
#[1] 3.333333 3.333333 3.333333 3.333333 3.333333 3.333333 3.333333

#$v
#[1] 2 3 4 5 6 7 8

这篇关于如何在多列数据表上滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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