不使用for循环,向前计算平均值

3

我的数据框长这样:

BookValue  Maturity   Yield   Weight
       20      2018   4.000  0.00282
       30      2019   4.550  0.00424
       70      2026   1.438  0.00989
       80      2026   1.438  0.01131
       60      2043   0.000  0.00848
       40      2043   0.000  0.00565

我希望计算出所有年份的总图书价值之和,每次减少一年,以得到以下输出结果:
Year       Book Value
2018-2043         300 
2019-2043         280
2026-2043         250
2043              100

如何实现不使用for循环的方式实现,是否可行?

3个回答

4

使用base方法,您可以使用rev()cumsum()函数。

val <- tapply(df$BookValue, df$Maturity, sum)
rev(cumsum(rev(val)))

# 2018 2019 2026 2043 
#  300  280  250  100
数据
df <- data.frame(BookValue = c(20, 30, 70, 80, 60, 40),
                 Maturity = c(2018, 2019, 2026, 2026, 2043, 2043))

完美的,非常感谢你。 - Christian

2

以下是使用base函数的一种可能方法:

#aggregate by year first
ans <- aggregate(dat$BookValue, list(dat$Maturity), sum)
N <- nrow(ans)

#then sum from 1:N, 2:N, 3:N, and so on
if (nrow(ans) >= 1) {
    ans$BVSum <- sapply(1:N, function(n) sum(ans$x[ n:N ]))
}

数据:

dat <- read.table(text="BookValue  Maturity   Yield  Weight
20      2018     4.000  0.00282
30      2019     4.550  0.00424
70      2026     1.438  0.00989
80      2026     1.438  0.01131
60      2043     0.000  0.00848
40      2043     0.000  0.00565", header=TRUE)

2

另一种选择:

# Assuming df is in order we extract first row for each year:
frow <- which(!duplicated(df$Maturity))
n <- nrow(df)


tbv <- lapply(
  frow, 
  function(x) {
    data.frame(
      year = paste0(df$Maturity[x], "-", df$Maturity[n]),
      book_value = sum(df$BookValue[x:n])
    )
  }
)
do.call(rbind, tbv)
       year book_value
1 2018-2043        300
2 2019-2043        280
3 2026-2043        250
4 2043-2043        100

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接