【发布时间】:2020-10-30 10:09:34
【问题描述】:
我很想分析多家公司的每月股票回报(面板数据)。但是,我正在努力计算公司过去 X 个月的标准差。
基本上,我想在现有的 data.frame 中添加另一列,其中显示了根据公司 X 个月移动窗口的标准偏差。请在下面找到我的数据的简化示例以及我希望实现的目标。
#My data:
company = c("1","1","1","1","1","2","2","2","2","2","2","2","3","3","3","3","4","4","4")
return = c(0.01,0.015,-0.01,0.02,0.023,-0.04,-0.02,-0.01,0.05,0.06,0.03,-0.09,0.2,0.3,-0.04,-0.02,-0.01,0.023,-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.015,-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 还很陌生。
*旁注: 研究这个问题和调整其他解决方案总是会导致这个错误:replacement has X rows, data has Y * where X >>> Y
【问题讨论】:
标签: r standard-deviation panel-data