我的数据框如下所示:
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循环,这是怎么可能的呢?
发布于 2018-07-12 18:17:45
通过base方式,您可以使用rev()和cumsum()。
val <- tapply(df$BookValue, df$Maturity, sum)
rev(cumsum(rev(val)))
# 2018 2019 2026 2043
# 300 280 250 100Data
df <- data.frame(BookValue = c(20, 30, 70, 80, 60, 40),
Maturity = c(2018, 2019, 2026, 2026, 2043, 2043))发布于 2018-07-12 18:17:17
以下是使用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)发布于 2018-07-12 18:37:32
另一种选择:
# 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 100https://stackoverflow.com/questions/51302572
复制相似问题