R Panel数据:基于ifelse语句和上一行创建新变量

问题描述

我的问题涉及以下(简化的)面板数据,我想为其创建某种xrd_stock

#Setup data
library(tidyverse)

firm_id <- c(rep(1,5),rep(2,3),rep(3,4))
firm_name <- c(rep("Cosco",rep("Apple",rep("BP",4))
fyear <- c(seq(2000,2004,1),seq(2003,2005,seq(2005,2008,1))
xrd <- c(49,93,121,84,37,197,36,154,104,116,6,21)
df <- data.frame(firm_id,firm_name,fyear,xrd)

#Define variables
growth = 0.08
depr = 0.15

对于名为xrd_stock的新变量,我想应用以下机制:

  1. 每个firm_id应该单独处理:group_by(firm_id)
  2. 在fyear最小的情况下,将xrd_stock计算为:xrd/(growth + depr)
  3. 否则,将xrd_stock计算为:xrd + (1-depr) * [xrd_stock from prevIoUs row]

通过以下代码,我已经成功完成了步骤1和2.。以及步骤3的部分操作。

df2 <- df %>%
  ungroup() %>%
  group_by(firm_id) %>%
  arrange(firm_id,decreasing = TRUE) %>% #Ensure that data is arranged w/ in asc(fyear) order; not required in this specific example as df is already in correct order
  mutate(xrd_stock = ifelse(fyear == min(fyear),xrd/(growth + depr),xrd + (1-depr)*lag(xrd_stock))))

函数else部分出现困难,使得R返回:

Error: Problem with `mutate()` input `xrd_stock`.
x object 'xrd_stock' not found
i Input `xrd_stock` is `ifelse(...)`.
i The error occured in group 1: firm_id = 1.
Run `rlang::last_error()` to see where the error occurred.

从此错误消息中,我了解到R无法引用上一行中刚创建的xrd_stock(在考虑/假设R并非严格地从上到下工作时,这是逻辑上的);但是,仅将9放在else部分中时,我上面的代码运行没有任何错误

任何人都可以帮助我解决此问题,以便最终看起来如下图所示。如果需要,我很乐意回答其他问题。预先感谢大家,我看着我的问题:-)

目标结果(Excel计算):

id  name    fyear   xrd xrd_stock   Calculation for xrd_stock
1   Cosco   2000    49  213         =49/(0.08+0.15)
1   Cosco   2001    93  274         =93+(1-0.15)*213
1   Cosco   2002    121 354         …
1   Cosco   2003    84  385         …
1   Cosco   2004    37  364         …
2   Apple   2003    197 857         =197/(0.08+0.15)
2   Apple   2004    36  764         =36+(1-0.15)*857
2   Apple   2005    154 803         …
3   BP      2005    104 452         …
3   BP      2006    116 500         …
3   BP      2007    6   431         …
3   BP      2008    21  388         …

解决方法

arrange的数据是fyear,因此最小年份始终是第一行,然后可以使用accumulate进行计算。

library(dplyr)
df %>%
  arrange(firm_id,fyear) %>%
  group_by(firm_id) %>%
  mutate(xrd_stock = purrr::accumulate(xrd[-1],~.y + (1-depr) * .x,.init = first(xrd)/(growth + depr)))

#   firm_id firm_name fyear   xrd xrd_stock
#     <dbl> <chr>     <dbl> <dbl>     <dbl>
# 1       1 Cosco      2000    49      213.
# 2       1 Cosco      2001    93      274.
# 3       1 Cosco      2002   121      354.
# 4       1 Cosco      2003    84      385.
# 5       1 Cosco      2004    37      364.
# 6       2 Apple      2003   197      857.
# 7       2 Apple      2004    36      764.
# 8       2 Apple      2005   154      803.
# 9       3 BP         2005   104      452.
#10       3 BP         2006   116      500.
#11       3 BP         2007     6      431.
#12       3 BP         2008    21      388.