使用Dplyr计算组之间的百分比变化-股票数据

时间:2020-02-07 02:34:37

标签: r dplyr stock

仅尝试计算给定时间段内每种股票的变化百分比。我当前使用dplyr的代码如下:

stocks_df %>%
filter(Date > now() - days(2)) %>%
group_by(Stock) %>%
mutate(period_return = (Close - first(Close))/ first(Close) * 100) %>%
do(tail(., n=1))


Date       Stock   Close 
2020-02-05 AAPL   308.86 
2020-02-04 AAPL   318.85 
2020-02-03 AAPL   321.45 
2020-02-05 BA     329.55 
2020-02-04 BA     317.94 
2020-02-03 BA     316 
2020-02-05 MSFT   179.9 
2020-02-04 MSFT   180.12 
2020-02-03 MSFT   174.38 

所需的输出为:

AAPL -3.92%
BA   4.29%
MSFT 3.17%

1 个答案:

答案 0 :(得分:2)

我想您正在寻找的是:

library(dplyr)
df %>%
  group_by(Stock) %>%
  summarise(period_return = -(last(Close) - first(Close))/ last(Close) * 100)

# Stock period_return
#  <fct>         <dbl>
#1 AAPL          -3.92
#2 BA             4.29
#3 MSFT           3.17

这可以使用aggregate在基数R中完成

aggregate(Close~Stock, df, function(x) -(x[length(x)] - x[1])/x[length(x)] * 100)