Q:

Calculating percent change between groups using Dplyr - Stock Data

Simply trying to calculate the percent change across a given time period for each stock. My current code using dplyr is as follows:
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 

Desired output would be:
AAPL -3.92%
BA   4.29%
MSFT 3.17%

A:

I guess what you are looking for is : 
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

which can be done in base R using aggregate
aggregate(Close~Stock, df, function(x) -(x[length(x)] - x[1])/x[length(x)] * 100)

