使用data.table包将平均值滚动到R中的多个变量 [英] rolling average to multiple variables in R using data.table package

查看:85
本文介绍了使用data.table包将平均值滚动到R中的多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得我拥有的每个数字变量的滚动平均值。使用data.table包,我知道如何为单个变量计算。但是,我应该如何修改代码,使其一次可以处理多个变量,而不是修改变量名称并重复此过程几次?谢谢。

I would like to get rolling average for each of the numeric variables that I have. Using data.table package, I know how to compute for a single variable. But how should I revise the code so it can process multiple variables at a time rather than revising the variable name and repeat this procedure for several times? Thanks.

假设我还有其他名为 V2, V3和 V4的数字变量。

Suppose I have other numeric variables named as "V2", "V3", and "V4".

require(data.table)
setDT(data)
setkey(data,Receptor,date)
data[ , `:=` ('RollConc' = rollmean(AvgConc, 48, align="left", na.pad=TRUE)) , by=Receptor]

可以在以下位置找到我的示例数据的副本:
https://drive.google.com/file/d/0B86_a8ltyoL3OE9KTUstYmRRbFk/view?usp=sharing

A copy of my sample data can be found at: https://drive.google.com/file/d/0B86_a8ltyoL3OE9KTUstYmRRbFk/view?usp=sharing

我想获得每个接收者5小时滚动表示 AvgConc, TotDep, DryDep和 WetDep。

I would like to get 5-hour rolling means for "AvgConc","TotDep","DryDep", and "WetDep" by each receptor.

推荐答案

从您的描述中,您想要这样的东西,类似于在 data.table 之一小插曲

From your description you want something like this, which is similar to one example that can be found in one of the data.table vignettes:

library(data.table)
set.seed(42)
DT <- data.table(x = rnorm(10), y = rlnorm(10), z = runif(10), g = c("a", "b"), key = "g")
library(zoo)
DT[, paste0("ravg_", c("x", "y")) := lapply(.SD, rollmean, k = 3, na.pad = TRUE), 
   by = g, .SDcols = c("x", "y")]

这篇关于使用data.table包将平均值滚动到R中的多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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