r - 在 R 中复制 ewm pandas 函数
问题描述
我正在尝试在 R 中复制 ewm python ( https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ewm.html ) 函数但没有成功。
这是python代码:
import pandas as pd
df = pd.DataFrame({'B': [0:100]})
df.ewm(span=100).std()
我无法在 R 中得到相同(或相似)的结果。
解决方案
我已经从使用 R 的指数加权移动标准差的矢量化实现中更改了代码?让它更胖:
f <- function(y, m, alpha) {
weights <- (1 - alpha)^((m - 1):0)
ewma <- sum(weights * y) / sum(weights)
bias <- sum(weights)^2 / (sum(weights)^2 - sum(weights^2))
ewmsd <- sqrt(bias * sum(weights * (y - ewma)^2) / sum(weights))
ewmsd
}
test <- frollapply(df0, 1000, function(x) f(x, 1000, alpha))
其中 df0 是具有一列或向量的 df。
结果与从 python 函数生成的结果相同(到小数点后 5 位)。
推荐阅读
- jupyter-notebook - 如何从 Jupyter Notebook 制作精美的 PDF?
- xamarin - NSDictionary 到 Xamarin.iOS 中的 Json
- multithreading - C# 4.0 中的异步函数调用
- ssis - 如何修复“[OData Source [56]] 错误:无法从运行时连接管理器获取托管连接。” SSIS中的错误?
- laravel - Laravel - 队列作业不被重用?
- google-app-engine - 有没有办法在 Google App Engine 中查找实例的生成时间和其他详细信息?
- containers - 无服务器容器和具有自定义运行时灵活的 App Engine 之间有什么区别?
- r - 在 R 中的字符向量上使用扩展函数
- c++ - 如何完善转发成员变量
- xml - 如何在保留其子元素的同时删除父标签