【发布时间】:2021-09-01 18:02:35
【问题描述】:
我这里有这个数据框:
smallerDF <- structure(list(category = c("Opponent", "Opponent", "Opponent",
"Opponent", "P1", "P2", "P3", "P2", "P2", "Opponent", "Opponent",
"P1"), Event = c("Good Pass", "Good Pass", "Good Pass", "Turnover",
"Good Pass", "Good Pass", "Good Pass", "Good Pass", "Bad Pass",
"Intercepted Pass", "Bad Pass", "Good Pass"), Value = c(2, 2,
2, -3, 2, 2, 2, 2, -2, 1, -2, 2), `Score Sum` = c(2, 4, 6, 3,
2, 4, 6, 8, 6, 1, -1, 2)), row.names = c(NA, -12L), class = c("tbl_df",
"tbl", "data.frame"))
它包含 4 列和 12 行。第三列是根据事件分配的值。在第 4 列中,我尝试将这些值相加以获得滚动总和。因此,每当对手有一个事件时,他们的当前值将被添加到他们之前的得分总和中,对于 P1/P2/P3 类似。我已经能够将总和滚动到我期望的结果,直到第 10 行。
我这里写了以下代码:
for (i in 1:nrow(smallerDF)) {
#print(i)
if (smallerDF$Event[i] == "Good Pass") {
smallerDF$Value[i] <- 2
}
if (smallerDF$Event[i] == "Bad Pass") {
smallerDF$Value[i] <- -2
}
if (smallerDF$Event[i] == "Intercepted Pass") {
smallerDF$Value[i] <- 1
}
if (smallerDF$Event[i] == "Turnover") {
smallerDF$Value[i] <- -3
}
if (smallerDF$category[i] == "Opponent") {
#print(i)
if (i != 1 && smallerDF$category[i-1] == "Opponent") {
smallerDF$`Score Sum`[i] <- smallerDF$Value[i] + smallerDF$`Score Sum`[i-1]
}
}
else if (smallerDF$category[i] %in% dfList) {
if (i != 1 && smallerDF$category[i-1] %in% dfList) {
smallerDF$`Score Sum`[i] <- smallerDF$Value[i] + smallerDF$`Score Sum`[i-1]
}
}
}
由于我使用 [i-1],这一直有效到第 10 行,但我不知道如何让第 10 行引用回第 4 行(上次使用对手)以添加单元格 [10 ,3] 到单元格 [4,4] 上。
最终结果应该是这样的
category Event Value `Score Sum`
<chr> <chr> <dbl> <dbl>
1 Opponent Good Pass 2 2
2 Opponent Good Pass 2 4
3 Opponent Good Pass 2 6
4 Opponent Turnover -3 3
5 P1 Good Pass 2 2
6 P2 Good Pass 2 4
7 P3 Good Pass 2 6
8 P2 Good Pass 2 8
9 P2 Bad Pass -2 6
10 Opponent Intercepted Pass 1 4
11 Opponent Bad Pass -2 2
12 P1 Good Pass 2 8
我尝试合并使用此代码
dt <- data.table(smallerDF)
newDT <- dt[ , .SD[.N] , by = c("category") ]
但这仅返回类别中每个不同值的最后一行,而不是类别的最新/上一次出现。
任何帮助将不胜感激。谢谢
【问题讨论】:
-
第 12 行的总分是 8,不应该是 4 吗?
-
来自 dput 的单元格 [10,4] 中的 1 只是我将 [10,3] 中的 1 添加到 [10,4] 中的代码。单元格 [10,4] 应该将单元格 [10,3] 中的 1 与单元格 [4,4] 中的 3 相加,以获得预期输出中的 4。这样做是在上次使用对手时添加对 [4,4] 的引用,这对我来说是一个挑战。这更有意义吗? @akrun
-
@NadPat 最终是的,它应该是 4,但我试图通过将 P1/P2/P3 加在一起来简化问题,因此 [12,3] 中的 P1 值将被添加到P2在[9,4]中的得分总和
-
@akrun 我并不完全希望将行组合在一起,因为较大的 DF 会随着时间的推移而变化,我希望随着时间的推移看到分数总和(第 4 列)的趋势进行比较P1/2/3 和对手得分
标签: r