我有一组包含许多行和列的示例数据。我正在努力计算每月的回报。我过去使用excel做过但是找不到解决方案。
RETURNS =(THIS_MONTH_PRICE / PREVIOUS_MONTH_PRICE) - 1
DF1 =
Date Price Stock
输出:
1 1/31/2011 339.32 AAPL
2 2/28/2011 353.21 AAPL
3 3/31/2011 348.45 AAPL
4 4/29/2011 348.23 AAPL
5 5/31/2011 347.83 AAPL
6 6/30/2011 335.67 AAPL
7 7/29/2011 390.48 AAPL
8 8/31/2011 384.83 AAPL
DF2=
Date Price Stock RETURNS
1 1/31/2011 339.32 AAPL NA
2 2/28/2011 353.21 AAPL 0.040934811
3 3/31/2011 348.45 AAPL 0.040934811
4 4/29/2011 348.23 AAPL 0.040934811
5 5/31/2011 347.83 AAPL 0.040934811
6 6/30/2011 335.67 AAPL 0.040934811
7 7/29/2011 390.48 AAPL 0.16328537
8 8/31/2011 384.83 AAPL -0.014469371
任何人都可以帮我解决这个问题。感谢。
答案 0 :(得分:2)
如果您对仅使用基础R的解决方案感兴趣:
> DF1$RETURNS <- (df$Price / c(0, head(df$Price, -1))) - 1
> DF1
Date Price Stock RETURNS
1 1/31/2011 339.32 AAPL Inf
2 2/28/2011 353.21 AAPL 0.0409348108
3 3/31/2011 348.45 AAPL -0.0134764021
4 4/29/2011 348.23 AAPL -0.0006313675
5 5/31/2011 347.83 AAPL -0.0011486661
6 6/30/2011 335.67 AAPL -0.0349596067
7 7/29/2011 390.48 AAPL 0.1632853696
8 8/31/2011 384.83 AAPL -0.0144693710
答案 1 :(得分:1)
我们可以使用dplyr包中的lag
函数。
library(dplyr)
df2 <- df1 %>% mutate(RETURNS = Price/lag(Price) - 1)
df2
# Date Price Stock RETURNS
# 1 1/31/2011 339.32 AAPL NA
# 2 2/28/2011 353.21 AAPL 0.0409348108
# 3 3/31/2011 348.45 AAPL -0.0134764021
# 4 4/29/2011 348.23 AAPL -0.0006313675
# 5 5/31/2011 347.83 AAPL -0.0011486661
# 6 6/30/2011 335.67 AAPL -0.0349596067
# 7 7/29/2011 390.48 AAPL 0.1632853696
# 8 8/31/2011 384.83 AAPL -0.0144693710
数据强>
df1 <- read.table(text = " Date Price Stock
1 '1/31/2011' 339.32 AAPL
2 '2/28/2011' 353.21 AAPL
3 '3/31/2011' 348.45 AAPL
4 '4/29/2011' 348.23 AAPL
5 '5/31/2011' 347.83 AAPL
6 '6/30/2011' 335.67 AAPL
7 '7/29/2011' 390.48 AAPL
8 '8/31/2011' 384.83 AAPL",
header = TRUE, stringsAsFactors = FALSE)