我想对data.table
个对象进行移动平均(最好是女巫自定义权重).frollmean
比frollapply
(特别是)甚至TTR::EMA
(不允许自定义权重,而只允许Wilder=T/F)要快得多--最后进行性能比较.我try 使用data.table:::froll
(frollmean
使用它,并且不会导出).它的第一个参数必须是函数的(字符)名称(对于frollmean
,它是mean
).
data.table:::froll('f.roll', x$c, 10)
Error in data.table:::froll("f.roll", x$c, 10) :
Internal error: invalid fun argument in rolling function, should have been caught before. please report to data.table issue tracker.
我try 将data.table包作为一个环境进行访问:
e.dt <- as.environment('package:data.table')
e.dt$froll <- data.table:::froll
Error in e.dt$froll <- data.table:::froll (from c.ta.R#287) :
cannot add bindings to a locked environment
e.dt2 <- new.env(parent=e.dt)
e.dt2$froll <- data.table:::froll
e.dt2$froll('f.roll', top.., n, na.rm=T)
Error in e.dt2$froll("f.roll", x$c, n, na.rm = T) :
Internal error: invalid fun argument in rolling function, should have been caught before. please report to data.table issue tracker.
我还try 将我的定制函数f.roll
附加到e.dt2
:
e.dt2$f.roll <- f.roll
e.dt2$froll('f.roll', top.., n, na.rm=T)
Error in e.dt2$froll("f.roll", top.., n, na.rm = T) :
Internal error: invalid fun argument in rolling function, should have been caught before. please report to data.table issue tracker.
froll
调用C函数(CfrollfunR
):
data.table:::froll
function (fun, x, n, fill = NA, algo = c("fast", "exact"), align = c("right",
"left", "center"), na.rm = FALSE, hasNA = NA, adaptive = FALSE)
{
stopifnot(!missing(fun), is.character(fun), length(fun) ==
1L, !is.na(fun))
algo = match.arg(algo)
align = match.arg(align)
ans = .Call(CfrollfunR, fun, x, n, fill, algo, align, na.rm,
hasNA, adaptive)
ans
}
<bytecode: 0x0000000013738b40>
<environment: namespace:data.table>
data.table:::CfrollfunR
$name
[1] "CfrollfunR"
$address
<pointer: 0x000000001ef93e80>
attr(,"class")
[1] "RegisteredNativeSymbol"
$dll
DLL name: datatable
Filename: C:/bin/cygwin/cygwin64/home/Adi/R/win-library/4.0/data.table/libs/x64/datatable.dll
Dynamic lookup: FALSE
$numParameters
[1] -1
attr(,"class")
[1] "CallRoutine" "NativeSymbolInfo"
然而,虽然我的定制函数f.roll
不起作用,但作为第一个参数的mean
起作用:
tail(e.dt2$froll('mean', x$c, 10, na.rm=T))
[1] 43.506 43.148 42.855 42.548 42.331 42.200
我判断了data.table DLLC:\bin\cygwin\cygwin64\home\Adi\R\win-library\4.0\data.table\libs\x64\datatable.dll
(使用DLL Export Viewer
),但它没有显示任何名为mean
的函数.data.table
包也没有任何mean
函数(导出或未导出).
data.table:::mean
Error in get(name, envir = asNamespace(pkg), inherits = FALSE) :
object 'mean' not found
data.table::mean
Error: 'mean' is not an exported object from 'namespace:data.table'
任何建议都将不胜感激.
PS以下是从microbenchmark
开始的性能比较,以供参考:
## Unit: milliseconds
## expr min lq mean median uq max neval
## frollapply 131736.6469 131736.6469 131736.6469 131736.6469 131736.6469 131736.6469 1
## EMA 262.9931 262.9931 262.9931 262.9931 262.9931 262.9931 1
## frollmean 97.0388 97.0388 97.0388 97.0388 97.0388 97.0388 1
PS因为froll
不是我的问题的解决方案(正如@Waldi指出的那样)我正在寻找替代的解决方案,但我保持现状,问了一个单独的新问题:fast way to calculate moving average/rolling function which allows custom weights