R 中 NA 的累积回报 [英] Cumulative Returns with NA's in R
问题描述
我有以下数据框:
df <- data.frame(Return1=c(NA, NA, .03, .04, .05),
Return2=c(.25, .33, NA, .045, .90),
Return3=c(.04, .073, .08, .04, .01))
Return1 Return2 Return3
1 NA 0.250 0.040
2 NA 0.330 0.073
3 0.03 NA 0.080
4 0.04 0.045 0.040
5 0.05 0.900 0.010
我想计算累积回报,但数据框中缺少值.我用过:
I would like to compute the cumulative returns, but there are missing values in the dataframe. I used:
cumprod(df+1)-1
得到结果
Return1 Return2 Return3
1 NA 0.2500 0.0400000
2 NA 0.6625 0.1159200
3 NA NA 0.2051936
4 NA NA 0.2534013
5 NA NA 0.2659354
这里的问题是,如果有一个 NA,后面的后续行将作为结果 NA.有没有一种方法可以在不影响下面其余行的情况下计算累积回报?
The problem here is that if there is a NA, the subsequent rows down will have as a Result NA. Is there a way to compute the cumulative returns without NA's affecting the rest of the rows below?
我想得到这样的结果:
Return1 Return2 Return3
1 NA 0.2500 0.0400000
2 NA 0.6625 0.1159200
3 0.03 NA 0.2051936
4 0.07120 0.7373 0.2534013
5 0.12476 2.3008 0.2659354
我知道 PerformanceAnalytics 包中有一个名为 Return.cumulative 的函数,但这只会获得整列的累积回报.
I know of a function in the PerformanceAnalytics package called Return.cumulative,but this will only obtain the cumulative return of the entire columns.
有什么想法吗?
推荐答案
cumpfun <- function(x){
x[!is.na(x)] <- cumprod(x[!is.na(x)]+1)-1
x
}
sapply(df,cumpfun)
# Return1 Return2 Return3
# [1,] NA 0.2500000 0.0400000
# [2,] NA 0.6625000 0.1159200
# [3,] 0.03000 NA 0.2051936
# [4,] 0.07120 0.7373125 0.2534013
# [5,] 0.12476 2.3008937 0.2659354
注意 sapply
返回一个矩阵.如果你需要一个数据框,你可以使用诸如 as.data.frame(lapply(df, cumpfun))
Note that sapply
returns a matrix. If you need a data frame, you could use sth like as.data.frame(lapply(df, cumpfun))
这篇关于R 中 NA 的累积回报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!