改进 data.table 中滚动平均值的使用

问题描述 投票:0回答:1

我正在尝试组合一个函数来复制以下内容

library(tidyverse)
library(magrittr)
library(data.table)
library(parallel)
library(RcppRoll)

windows <- (1:10)*600

df2 <- setDT(df_1, key=c("Match","Name"))[
  ,by=.(Match, Name), paste0("Period_", 1:10)
  := mclapply((1:10)*600, function(x) roll_mean(Dist, x))][]

它根据分配给

windows
的值创建滚动平均值 我有一个可以复制它的工作函数,但是我感觉有更好的方法来实现它,因为该函数版本处理数据所需的时间几乎长了 30 倍

dt_rolling <- function(df, the.keys, x, y, z, window){
  df <- data.table(df)
  setkeyv(df, the.keys) 
  df[,by=.(x,y), paste0("Period_", window) := mclapply(window, function(a) roll_mean(z, a))][]
}


df2 <- dt_rolling(df_1, the.keys=c('Match', 'Name'), df_1$Match, df_1$Name, df_1$Dist, windows)

有问题的数据看起来像这样

> dput(head(df_1, 5))
structure(list(Match = c("BathH", "BathH", "BathH", "BathH", 
"BathH"), Name = c("Alafoti Faosiliva", "Alafoti Faosiliva", 
"Alafoti Faosiliva", "Alafoti Faosiliva", "Alafoti Faosiliva"
), Dist = c(0, 0, 0, 0, 0), Period_1 = c(NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_), Period_2 = c(NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_), Period_3 = c(NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_), Period_4 = c(NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_), Period_5 = c(NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_), Period_6 = c(NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_), Period_7 = c(NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_), Period_8 = c(NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_), Period_9 = c(NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_), Period_10 = c(NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_), Period_600 = c(NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_), Period_1200 = c(NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_), Period_1800 = c(NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_), Period_2400 = c(NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_), Period_3000 = c(NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_), Period_3600 = c(NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_), Period_4200 = c(NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_), Period_4800 = c(NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_), Period_5400 = c(NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_), Period_6000 = c(NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_)), sorted = c("Match", "Name"), class =     c("data.table", 
"data.frame"), row.names = c(NA, -5L), .internal.selfref = <pointer:   0x10280cae0>)

它可以扩展到超过 2000 万行,所以这就是为什么我在这里使用

data.table
方法并研究将其更改为函数

r data.table
1个回答
7
投票

自 v1.12.0 版本起,data.table 中提供快速滚动平均值。
以下查询将解决您的问题。

df_1[, paste0("Period_", windows) := frollmean(Dist, windows)]
© www.soinside.com 2019 - 2024. All rights reserved.