-1

I have the following data:

structure(list(`Product Name` = c("A", "A", "A", "B", "B", "B", 
"C", "C", "C"), Year = c(2018L, 2019L, 2020L, 2018L, 2019L, 2020L, 
2018L, 2019L, 2020L), Price = c(200L, 300L, 250L, 304L, 320L, 
103L, 203L, 203L, 402L)), class = "data.frame", row.names = c(NA, 
-9L))

Now I would like to compute the yearly continuous return based on the following formula: ln(Price_t /Price_(t-1)) where t represents the year.

I came across the following question: Calculating monthly returns based on Panel Data R However, I have a different formula for the return.

Could someone help me with the code? Thanks a lot in advance.

nima
  • 37
  • 6

1 Answers1

1

You can use the lag function from dplyr to get the previous period returns and group by product name to perform your calculation.

library(dplyr)
df <- df %>% 
    group_by(`Product Name`) %>% 
    mutate(return = log(Price / dplyr::lag(Price)))
# A tibble: 9 x 4
# Groups:   Product Name [3]
# `Product Name`  Year Price  return
# <chr>          <int> <int>   <dbl>
#     1 A        2018   200 NA     
#       A        2019   300  0.405 
#       A        2020   250 -0.182 
#       B        2018   304 NA     
#       B        2019   320  0.0513
#       B        2020   103 -1.13  
#       C        2018   203 NA     
#       C        2019   203  0     
#       C        2020   402  0.683 
AdroMine
  • 1,427
  • 5
  • 9
  • Thank you AdroMine for you quick response! How can you avoid that for Product B in year 2018 the return is calculated based on Product A's price in 2020? The same for Product C's return in 2018. It should be NA. – nima Mar 25 '22 at 16:04
  • 1
    it *does* get calculated as NA for 2018 for all products. `group_by` ensures that `mutate` only uses the data of it's own group in the calculation. – AdroMine Mar 25 '22 at 16:15
  • I am sorry but when I run the code, it does not get calculated as NA. I have the dplyr package installed and open in the library. – nima Mar 25 '22 at 16:21
  • 1
    most likely your product name column is named differently? – AdroMine Mar 25 '22 at 16:25
  • Thank you for the input! The problem was that I had group_by("Product Name") instead of group_by(Product Name). Really appreciate your help and your quick answers! – nima Mar 25 '22 at 16:34
  • If it worked, do accept this as answer – AdroMine Mar 25 '22 at 17:18