我仍然是新手数据争吵-R并且正在努力寻找解决方案。
以下是我的月度百分比变化的数据框:
Month Security1 Security2 ... SecurityN
1970-01 -2.30% 1.02% 0.64%
1970-02 1.87% -0.01% 9.50%
1970-03 3.38% 2.33% 5.56%
我试图获得一个数据框,每个安全的月度回报(> 1500)被索引以显示累积回报,如下所示:
Month Security1 Security2 ... SecurityN
1970-01 100 100 100
1970-02 101.87 99.99 109.50
1970-03 105.32 102.32 115.59
我尝试过使用:
cum.ret <- apply(dataframe, 2, function(x) Return.cumulative(x, geometric = TRUE))
但这只能回报自成立以来每只股票的价格: Security1返回121%,Security2返回233%等
除了加载数据外,笔记本中还没有其他代码。
非常感谢任何帮助!
答案 0 :(得分:2)
可能的解决方案:
mydf[-1] <- lapply(mydf[-1], function(x) as.numeric(sub('%','',x)))
mydf[1,-1] <- 100
mydf[-1] <- lapply(mydf[-1], cumsum)
给出:
> mydf Month Security1 Security2 SecurityN 1 1970-01 100.00 100.00 100.00 2 1970-02 101.87 99.99 109.50 3 1970-03 105.25 102.32 115.06
使用过的数据:
mydf <- read.table(text="Month Security1 Security2 SecurityN
1970-01 -2.30% 1.02% 0.64%
1970-02 1.87% -0.01% 9.50%
1970-03 3.38% 2.33% 5.56%", header=TRUE, stringsAsFactors=FALSE)