【问题标题】:R diff -what is the equivalent to D.x in Stata of panel data to generate differenced variablesR diff - 什么相当于面板数据Stata中的D.x生成差异变量
【发布时间】:2023-03-22 19:27:01
【问题描述】:

在 R 中添加差异变量的正确语法是什么?类似于 Stata 中的“D.variable”命令。 我尝试在 R 中生成差异变量。我尝试了几种方法,但我无法获得与 Stata 相同的输出。 R代码:

DF <- DF%>%
   group_by(id) %>%
   mutate(D_MDR = F_MDR - dplyr::lag(F_MDR)) 
 summary(DF$D_MDR)

输出:

 Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
-0.7724 -0.1456 -0.0098 -0.0113  0.1232  0.8416    1441 

R 代码:

DFP1 <- pdata.frame(DF, index = c("id"))
DFP1$D_MDR <- diff(DFP1$F_MDR,lag = 1, differences = 1) 
skim(DFP1$D_MDR)

输出:

-- Data Summary ------------------------
                           Values    
Name                       DFP1$D_MDR
Number of rows             10433     
Number of columns          1         
_______________________              
Column type frequency:               
  numeric                  1         
________________________             
Group variables            None      

-- Variable type: numeric ----------------------------------------------------------------------------------
# A tibble: 1 x 11
  skim_variable n_missing complete_rate    mean    sd     p0    p25      p50   p75  p100 hist 
* <chr>             <int>         <dbl>   <dbl> <dbl>  <dbl>  <dbl>    <dbl> <dbl> <dbl> <chr>
1 data               1441         0.862 -0.0113 0.207 -0.772 -0.146 -0.00978 0.123 0.842 ▁▃▇▂▁

这是Stata代码:

 tsset id year
 gen D_MDR = D.F_MDR
 sum D_MDR

状态输出:


    Variable |        Obs        Mean    Std. Dev.       Min        Max
-------------+---------------------------------------------------------
       D_MDR |     11,644    .0067983    .1438224  -.8537842   .8227942

【问题讨论】:

标签: r diff stata panel-data


【解决方案1】:

如果你想使用 plm 包中的 diff,这应该可以让你到达你想要的地方:

DFP1 <- pdata.frame(DF, index = c("id", "year"))
DFP1$D_MDR <- diff(DFP1$F_MDR)

相对于您的代码,我在pdata.frame 的索引参数中添加了时间维度。我删除了diff 的参数(lag = 1 是默认值,difference 不是plm::diff 的有效参数)。

请注意,plm::diff 默认尝试按时间移动(不是逐行,行为可以由 shift 参数控制),如果它可以正确解释时间维度(最好使用整数值作为时间维度)。

【讨论】:

    猜你喜欢
    • 2016-11-21
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多