我有以下数据框:
dat <- tibble::tribble( ~date , ~pct_monthly_return,
2021-01-31, 0.0023,
2021-02-28, 0.01,
2021-03-31, 0.035)
Run Code Online (Sandbox Code Playgroud)
我想创建一个名为的新列,index
该列从数据帧开始前一个月的 100 开始(即我的示例中的 2020-12-31)。然后,指数 100 必须与pct_monthly_return
变量相乘,以便我可以看到指数如何随着时间的推移而增长。
结果应产生以下数据框:
date pct_monthly_return index
2020-12-31 0 100
2021-01-31 0.0023 100.23
2021-02-28 0.01 101.2323
2021-03-31 0.035 104.7754
Run Code Online (Sandbox Code Playgroud)
我们可以将收益的累积乘积表示为系数,即1 + pct_monthly_return
dat$index = 100 * cumprod(1+dat$pct_monthly_return)
Run Code Online (Sandbox Code Playgroud)
然后添加您描述的标题行:
rbind(data.frame(date = "2020-12-31", index = 100, pct_monthly_return = 0),
dat)
date index pct_monthly_return
1 2020-12-31 100.0000 0.0000
2 2021-01-31 100.2300 0.0023
3 2021-02-28 101.2323 0.0100
4 2021-03-31 104.7754 0.0350
Run Code Online (Sandbox Code Playgroud)
样本数据
dat <- tibble::tribble( ~date , ~pct_monthly_return,
"2021-01-31", 0.0023,
"2021-02-28", 0.01,
"2021-03-31", 0.035)
Run Code Online (Sandbox Code Playgroud)
基础R:
使用sapply
和cumprod
:
> cbind(dat, index=as.vector(sapply(dat[,-1] + 1, cumprod) * 100))
date pct_monthly_return index
1 2021-01-31 0.0023 100.2300
2 2021-02-28 0.0100 101.2323
3 2021-03-31 0.0350 104.7754
>
Run Code Online (Sandbox Code Playgroud)
或者甚至更好:
> cbind(dat, index=cumprod(1 + dat$pct_monthly_return) * 100)
date pct_monthly_return index
1 2021-01-31 0.0023 100.2300
2 2021-02-28 0.0100 101.2323
3 2021-03-31 0.0350 104.7754
>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
807 次 |
最近记录: |