R:面板数据的连续返回



我有以下数据:

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))

现在我想根据以下公式计算年度连续回报率:ln(Price_t/Price_(t-1((,其中t表示年份。

我遇到了以下问题:根据面板数据R计算月度回报然而,我有一个不同的回报公式。

有人能帮我查一下密码吗?提前非常感谢。

您可以使用dplyr中的滞后函数来获取上期回报,并按产品名称分组进行计算。

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 

最新更新