【问题标题】:Including trend to data frame with different numbers of observed years包括具有不同观测年数的数据框的趋势
【发布时间】:2020-12-02 20:28:13
【问题描述】:

让我们考虑删除了 300 行的面板数据

data("EmplUK", package="plm")
set.seed(42)
EmplUK<-EmplUK[-sample(1:nrow(EmplUK),300),]
  firm year sector    emp    wage capital   output
1    1 1977      7  5.041 13.1516  0.5894  95.7072
4    1 1980      7  4.715 13.8039  0.6171 100.5501
5    1 1981      7  4.093 14.2897  0.5076  99.5581
6    1 1982      7  3.166 14.8681  0.4229  98.6151
7    1 1983      7  2.936 13.7784  0.3920 100.0301
8    2 1977      7 71.319 14.7909 16.9363  95.7072

我想为这个数据框添加一个趋势,即从 1 开始的数字:每个公司的某个值。

问题是每个公司都没有一些观察年份,即公司有 1977、1980、1981、1982 年(所以公司 1 的趋势向量应该是:1、2、3、4)。公司三有 1977,1979,1980,1981,1982,1983(公司三的趋势向量应该是:1,2,3,4,5,6)。

我不太确定如何轻松完成。我知道对于每个公司,我可以创建unique() 年向量并计算1:length(uniqie())。没关系,有没有更简单的方法可以实现?

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    不确定您想要什么,但请使用dplyr 尝试这种方法:

    library(dplyr)
    data("EmplUK", package="plm")
    set.seed(42)
    EmplUK<-EmplUK[-sample(1:nrow(EmplUK),300),]
    #Code
    New <- EmplUK %>% group_by(firm) %>% mutate(Trend=row_number())
    

    输出:

    # A tibble: 731 x 8
    # Groups:   firm [140]
        firm  year sector   emp  wage capital output Trend
       <dbl> <dbl>  <dbl> <dbl> <dbl>   <dbl>  <dbl> <int>
     1     1  1977      7  5.04  13.2   0.589   95.7     1
     2     1  1980      7  4.72  13.8   0.617  101.      2
     3     1  1981      7  4.09  14.3   0.508   99.6     3
     4     1  1982      7  3.17  14.9   0.423   98.6     4
     5     1  1983      7  2.94  13.8   0.392  100.      5
     6     2  1977      7 71.3   14.8  16.9     95.7     1
     7     2  1978      7 70.6   14.1  17.2     97.4     2
     8     2  1980      7 72.0   15.5  17.7    101.      3
     9     2  1982      7 72.4   16.1  16.2     98.6     4
    10     3  1977      7 19.2   22.7   7.10    95.7     1
    # ... with 721 more rows
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-03
      • 2018-09-09
      • 1970-01-01
      相关资源
      最近更新 更多