如何在 R 中创建新列计算按变量(因子)分组的数值变量的平均值(前 3 个分组行)?
我尝试过使用 rollapply 但无法获得所需的结果。
这些是我想要进行计算的数据集的列(样本)。
structure(list(LeagueROUND = structure(c(1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 4L), .Label = c("1", "2",
"3", "4"), class = "factor"), League = structure(c(1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "Portugal2", class = "factor"),
Season = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L), .Label = "2021/2022", class = "factor"),
DRAWmarginODDS = structure(c(2L, 1L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L), .Label = c("No", "Yes"), class = "factor"),
DRAWnumODDS = c(0L, NA, 0L, 1L, 0L, 0L, 1L, 1L, 0L, 0L, 0L,
0L, 0L, NA, 0L)), .Names = c("LeagueROUND", "League", "Season",
"DRAWmarginODDS", "DRAWnumODDS"), class = "data.frame", row.names = c(NA,
-15L))
所需结果
分组依据(LeagueROUND,League,Season,DRAWmarginODDS)
(DRAWnumODDS) 的平均值前 3 个 LeagueROUND
即:
联赛第 1 轮(是)在 3(分组)行中添加 1(DRAWnumODDS)。
联赛第 2 轮(是)在 4(分组)行中添加 2(DRAWnumODDS)
联赛第 3 轮(是)在 3(分组)行中添加 0(DRAWnumODDS)
期望:
在联赛第 4 轮中(是)(前 3 轮联赛的平均值) = 3(DRAWnumODDS) in 10(grouped) rows = 平均值 0,3
League Round (No) = NA
3 First LeagueROUND ->不适用
I have tried using rollapply but I can't get the desired result.
These are the columns(sample) of the dataset on which I want to do the calculations.
structure(list(LeagueROUND = structure(c(1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 4L), .Label = c("1", "2",
"3", "4"), class = "factor"), League = structure(c(1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "Portugal2", class = "factor"),
Season = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L), .Label = "2021/2022", class = "factor"),
DRAWmarginODDS = structure(c(2L, 1L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L), .Label = c("No", "Yes"), class = "factor"),
DRAWnumODDS = c(0L, NA, 0L, 1L, 0L, 0L, 1L, 1L, 0L, 0L, 0L,
0L, 0L, NA, 0L)), .Names = c("LeagueROUND", "League", "Season",
"DRAWmarginODDS", "DRAWnumODDS"), class = "data.frame", row.names = c(NA,
-15L))
Desired result
Group by( LeagueROUND,League,Season,DRAWmarginODDS)
Average(mean) of (DRAWnumODDS) of 3 previous LeagueROUNDs
That is:
League Round 1 (Yes) adds 1(DRAWnumODDS) in 3(grouped) rows.
League Round 2 (Yes) adds 2(DRAWnumODDS) in 4(grouped) rows
League Round 3 (Yes) adds 0(DRAWnumODDS) in 3(grouped) rows
Desired:
In League Round 4(Yes) (average of 3 previous League Round) = 3(DRAWnumODDS) in 10(grouped) rows = mean 0,3
League Round (No) = NA
3 first LeagueROUND -> NA
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由 reprex 包 (v2.0.0) 创建于 2022 年 3 月 15 日
Created on 2022-03-15 by the reprex package (v2.0.0)