我的问题涉及以下(简化的)面板数据,我想为这些数据创建某种xrd_stock。
#Setup data
library(tidyverse)
firm_id <- c(rep(1, 5), rep(2, 3), rep(3, 4))
firm_name <- c(rep("Cosco", 5), rep("Apple", 3), rep("BP", 4))
fyear <- c(seq(2000, 2004, 1), seq(2003, 2005, 1), 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的新变量,我想应用以下机制:
应分别处理每个group_by(firm_id)
xrd/(growth + depr)
xrd/(growth + depr)
xrd + (1-depr) * [xrd_stock from previous row]使用下面的代码,我已经成功地完成了步骤1和2以及步骤3的部分。
df2 <- df %>%
  ungroup() %>%
  group_by(firm_id) %>%
  arrange(firm_id, fyear, 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         …发布于 2020-10-27 08:57:01
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.https://stackoverflow.com/questions/64550845
复制相似问题