r - 计算前 6 个数据点的平均值
问题描述
我有一个包含日期、唯一公司名称及其股票回报的数据表,看起来有点像这样:
require(data.table)
DATE <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
COMP <- c(replicate(60, "AAPL"), replicate(60, "INTL"), replicate(60, "GOOGL"), replicate(60, "MSFT"))
RET <- rnorm(240)
test1 <- data.table(DATE, COMP, RET)
现在我要计算每个数据点之前的平均 6 个同月日历回报。例如,对于 1990 年 1 月的 AAPL 股票收益,我希望在 Jan90 收益旁边的新列中获得 Jan89、Jan 88、...和 Jan84 收益的平均值。我试图习惯跳过行,但现在我有点卡住了。这是我用来玩这个机制的代码:
test1$new1 <- test1$RET[seq.int(from = 1L, to = 20L, by = 6L)]
test1$new2 <- test1$RET[seq.int(from = -20L, to = 0L, by = 6L)]
n = 6
test1$new3 <- rowMeans(test1[seq(from = 1, to = nrow(test1), by = n),])
有谁知道,如何做到这一点?
原因,为什么它与其他问题不同:这里的关键点是只取以前的值,同时只考虑某家公司。此外,它应该只是作为新列添加。
PS:我不致力于数据表,到目前为止我只是很喜欢这个包。
解决方案
调整重复问题中已接受的答案以使其具有功能是一个问题。
然后,首先将输入数据集拆分为,计算均值并使用package"COMP"
中的函数将所有内容组合回一个数据集。bind_rows
dplyr
library(dplyr)
fun <- function(DF, col = "RET", n = 6){
aggregate(DF[[col]], list(rep(1:(nrow(test1)%/%n + 1), each = n, len = nrow(DF))), mean)
}
sp <- split(test1, test1$COMP)
res <- lapply(sp, fun)
res <- bind_rows(res, .id = "id")
推荐阅读
- javascript - 如何在内部实现带有 Promise 的渲染逻辑?
- php - 使用 PHP 以 CSV 文件格式下载
- node.js - multer req.body 总是显示为空
- git - 将主分支与开发同步
- visual-studio - ASP.NET Core 启动设置:IIS Express、IIS、项目、可执行文件
- android - 饼图显示剪切窗口属性更改未反映在使 videoview 全屏
- python - 计算模式同时忽略某些值
- apache - 使用 .htaccess 删除 URl 的某些部分?
- xamarin - 无法将类型“System.Windows.Input.ICommand”隐式转换为“Xamarin.Forms.Command”
- linux - dotnet restore 在配置有代理的 bitbucket 管道上失败