R:使用移动窗口按组计算标准偏差

问题描述

我想分析多家公司每月股票回报(面板数据)。但是,我一直在努力计算公司最近X个月的标准偏差

基本上,我想在现有data.frame中添加另一列,其中显示了根据公司移动X个月的窗口的标准差。请在下面的简化示例中找到我的数据以及我希望实现的目标。

#My data:
company = c("1","1","2","3","4","4")
return = c(0.01,0.015,-0.01,0.02,0.023,-0.04,-0.02,0.05,0.06,0.03,-0.09,0.2,0.3,-0.04)
stock = data.frame(company,return)

鉴于这种初始情况,我希望根据另一种方法在另一列中计算标准差。 3个观察结果。

#Column to be filled with the respective value
stock["std_3obs"] = NA
#However,I do not manage to fill this column accordingly. The following result for a given row is expected:
#row 1 = Not possible,as there are not enough prior observations available
#row 2 = Not possible,as there are not enough prior observations available
#row 3 = sd(c(0.01,-0.01) = 0.01322876
#row 7 = Not possible,as there are not enough prior observations available
#row 8 = sd(c(-0.040,-0.020,-0.010)) = 0.01527525

非常感谢!任何帮助深表感谢!请保持温柔,因为我对R还不熟悉。

* 侧面注释: 对此问题进行研究并采用其他解决方案总是会导致此错误:替换具有X行,数据具有Y *,其中X >>> Y

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)