简体   繁体   English

使用 data.table 包对 R 中的多个变量进行滚动平均

[英]rolling average to multiple variables in R using data.table package

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.使用 data.table 包,我知道如何计算单个变量。 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.谢谢。

Suppose I have other numeric variables named as "V2", "V3", and "V4".假设我有其他名为“V2”、“V3”和“V4”的数字变量。

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

A copy of my sample data can be found at: https://drive.google.com/file/d/0B86_a8ltyoL3OE9KTUstYmRRbFk/view?usp=sharing可以在以下位置找到我的示例数据的副本: https : //drive.google.com/file/d/0B86_a8ltyoL3OE9KTUstYmRRbFk/view?usp=sharing

I would like to get 5-hour rolling means for "AvgConc","TotDep","DryDep", and "WetDep" by each receptor.我想通过每个受体获得“AvgConc”、“TotDep”、“DryDep”和“WetDep”的 5 小时滚动方式。

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 :根据您的描述,您需要类似这样的内容,这类似于可以data.table小插图之一中找到的一个示例:

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")]

Now, one can use the frollmean function in the data.table package for this.现在,可以frollmean使用data.table包中的frollmean函数。

library(data.table)    
xy <- c("x", "y")
DT[, (xy):= lapply(.SD, frollmean, n = 3, fill = NA, align="center"), 
                                   by = g, .SDcols =  xy]

Here, I am replacing the x and y columns by the rolling average.在这里,我用滚动平均值替换 x 和 y 列。


# Data
set.seed(42)
DT <- data.table(x = rnorm(10), y = rlnorm(10), z = runif(10), 
                                g = c("a", "b"), key = "g")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM