【问题标题】:panel data: How to remove IDs with missing yearly information面板数据:如何删除缺少年度信息的 ID
【发布时间】:2019-02-25 21:31:32
【问题描述】:

我有一个包含 Id 年观察值的数据集。我想比较2015年前后/后的变化。因此我需要所有的公司在2015年前后/后都有观察,这样我才能比较。

ID year diesese
1 2012  3
1 2016  4
3 2013  3
3 2015  4
2 2012  3
2 2013  4

我的问题是如何删除仅在 2015 年之前或 2015 年之后观察到的公司?所以在上面的数据中,只有 ID=1 和 ID=3 符合我的需要,ID=2 没有。

【问题讨论】:

    标签: r time-series panel-data


    【解决方案1】:

    与tidyverse:

    df%>%
       mutate_all(as.numeric)%>%
       group_by(ID)%>%
       filter(ID %in% ID[any(year>=2015) & any(year<2015)])
    # A tibble: 4 x 3
    # Groups:   ID [2]
         ID  year diesese
      <dbl> <dbl>   <dbl>
    1    1. 2012.      3.
    2    1. 2016.      4.
    3    3. 2013.      3.
    4    3. 2015.      4.
    

    还是这个

    df%>%
      mutate_all(as.numeric)%>%
      group_by(ID)%>%
      filter(!ID %in% ID[all(year>2015) | all(year<2015)])
    

    【讨论】:

    • 谢谢!看起来第一个解决方案有效,而第二个解决方案仅在 2015 年和 2015 年之后的一年内让公司保持观察。
    【解决方案2】:

    这是另一种选择。我们遍历每个 ID 中的数据,并过滤任何 2015 年或以后没有任何数据的组。

    library(tidyverse)
    
    df %>%
      nest(-ID) %>%
      filter(map_dbl(data, ~length(which(.x$year >= 2015))) > 0) %>%
      unnest
    #> # A tibble: 4 x 3
    #>      ID  year diesese
    #>   <int> <int>   <int>
    #> 1     1  2012       3
    #> 2     1  2016       4
    #> 3     3  2013       3
    #> 4     3  2015       4
    

    由reprex package (v0.2.0) 于 2018 年 9 月 21 日创建。

    【讨论】:

      【解决方案3】:

      一个想法是使用 ave 与一个函数,该函数计算大于或等于 2015 的值的数量。!! 将其转换为逻辑,以便我们可以索引,即

      df[!!with(df, ave(year, ID, FUN = function(i)length(i[i >= 2015]) >= 1)),]
      

      给出,

      ID year disease
      1  1 2012       3
      2  1 2016       4
      3  3 2013       3
      4  3 2015       4
      

      @RonakShah 和 @Jaap 提供的更多选项,

      df[!with(df, ave(year, ID, FUN = function(x) all(x > 2015) | all(x < 2015)))), ]
      df[with(df, ave(year, ID, FUN = function(y) any(y >= 2015))),]
      

      【讨论】:

      • 另一个选项df[!with(df, ave(year, ID, FUN = function(x) all(x &gt; 2015) | all(x &lt; 2015)))), ] 或者如果你真的可以缩短条件。
      • 或:with(df, ave(year, ID, FUN = function(y) any(y &gt;= 2015)))
      • 非常感谢!但不知何故,结果包括仅在 2015 年或之后进行观察的公司。
      猜你喜欢
      • 2017-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多