对于具有三列的矩阵 .
ID t res
1 1 -1.5
1 2 -1.5
1 3 0.5
1 4 0.5
2 1 -0.5
2 2 -0.5
2 3 -2.0
2 4 -1.5
2 5 1.5
我的目标是像这样按 ID 对列 res 的值求和。
(-1.5*(-1.5+0.5+0.5) - 1.5*(0.5+0.5) + 0.5*(0.5))/(4-1) +
(-0.5*(-0.5-2.0-1.5+1.5) - 0.5*(-2.0-1.5+1.5) - 2.0*(-1.5+1.5) -1.5*(1.5))/(5-1)
= -0.167
非常感谢任何关于如何按组求和和划分的建议。
library(dplyr)
df1 %>%
group_by(ID) %>%
arrange(ID, desc(t)) %>%
mutate(hlc = cumsum(lag(res, default = 0)) * res / (n()-1) ) %>%
pull(hlc) %>% sum()
#> [1] -0.1666667
read.table(text = " ID t res
1 1 -1.5
1 2 -1.5
1 3 0.5
1 4 0.5
2 1 -0.5
2 2 -0.5
2 3 -2.0
2 4 -1.5
2 5 1.5", stringsAsFactors = F, header = T) -> df1
这是一个基本的 R 解决方案。
df1 <- "ID t res
1 1 -1.5
1 2 -1.5
1 3 0.5
1 4 0.5
2 1 -0.5
2 2 -0.5
2 3 -2.0
2 4 -1.5
2 5 1.5"
df1 <- read.table(text = df1, header = TRUE)
out <- tapply(df1$res, df1$ID, FUN = \(x) {
sum(sapply(seq_along(x), \(i) x[i]*sum(x[-(1:i)]))) / (length(x) - 1)
})
out <- sum(out)
out
#> [1] -0.1666667
创建于 2023-02-25 与 reprex v2.0.2