Search code examples
rdataframelapplyfinancecalculation

Calculation on one row of a Data Frame with the other row for calculating returns in R


I have a following set of sample data which has many rows and columns. I am trying to do calculate the monthly returns. I have done it in the past using excel but cannot find a solution for this.

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
OUTPUT:

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

Can anyone help me in solving this. Thanks.


Solution

  • We can use the lag function from the package.

    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
    

    DATA

    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)