【问题标题】:In R: subset so that I only have observations at least 3 years prior to and after an event在 R: 子集中,所以我只有在事件前后至少 3 年的观察结果
【发布时间】:2021-07-31 04:06:25
【问题描述】:

我之前问过以下问题:In R: subset so that I only have the observations 3 years prior to and after an event

我该如何做同样的事情,但限制是在日期之前或之后至少 3 年,而不是必须准确地在之前和之后 3 年?

如果我有这样的数据:

companyID   year   status
    1       2000     1
    1       2001     1
    1       2002     1
    1       2003     1
    1       2004     0
    1       2005     2
    1       2006     2
    1       2007     2
    2       2012     1
    2       2013     0
    2       2014     2
    2       2015     2
    2       2016     2
    3       2008     1
    3       2009     1
    3       2010     1
    3       2011     1
    3       2012     1
    3       2013     0
    3       2014     2
    3       2015     2
    3       2016     2
    3       2017     2

因此,我希望我的数据看起来像这样:

companyID   year   status
    1       2000     1
    1       2001     1
    1       2002     1
    1       2003     1
    1       2004     0
    1       2005     2
    1       2006     2
    1       2007     2
    3       2008     1
    3       2009     1
    3       2010     1
    3       2011     1
    3       2012     1
    3       2013     0
    3       2014     2
    3       2015     2
    3       2016     2
    3       2017     2

提前感谢您的指导!!

【问题讨论】:

    标签: r dplyr subset


    【解决方案1】:

    借助辅助函数,您可以做到:

    library(dplyr)
    
    select_rows <- function(status) {
      inds <- match(0, status)
      inds >= 4 && length(status) >= (inds + 3)
      #inds >= 4 ensures there are atleast 3 years before the event
      #length(status) >= (inds + 3) ensures there are atleast 3 years after
    }
    
    df %>%
      arrange(companyID, year) %>%
      group_by(companyID) %>%
      filter(select_rows(status)) %>%
      ungroup
    
    #   companyID  year status
    #       <int> <int>  <int>
    # 1         1  2000      1
    # 2         1  2001      1
    # 3         1  2002      1
    # 4         1  2003      1
    # 5         1  2004      0
    # 6         1  2005      2
    # 7         1  2006      2
    # 8         1  2007      2
    # 9         3  2008      1
    #10         3  2009      1
    #11         3  2010      1
    #12         3  2011      1
    #13         3  2012      1
    #14         3  2013      0
    #15         3  2014      2
    #16         3  2015      2
    #17         3  2016      2
    #18         3  2017      2
    

    【讨论】:

      猜你喜欢
      • 2021-07-19
      • 2017-11-09
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      • 1970-01-01
      • 2021-11-11
      • 2014-04-03
      • 2022-11-26
      相关资源
      最近更新 更多