【问题标题】:How to filter out one variable conditioned on the change in itself and another variable?如何过滤掉一个以自身变化为条件的变量和另一个变量?
【发布时间】:2021-03-02 18:50:23
【问题描述】:

我正在尝试从随时间推移跟踪个人的面板数据中的数据输入差异中清除我的年龄变量。许多受访者的年龄从一次观察到另一次跳跃是因为他们错过了几波然后又回来了,正如我们在下面 ID 1 和 2 的人中看到的那样。但是,ID 3 的人的年龄发生了跳跃这不等于他/她退出小组的那一年。

有人可以指导我如何从我的数据中过滤掉年龄不合理变化的受访者,这些变化不等于他们退出小组的年数而是其他原因,例如数据输入问题?

id  year    age
1   2005    50
1   2006    51
1   2010    55
2   2002    38
2   2005    41
2   2006    42
3   2006    30
3   2009    38
3   2010    39

structure(list(id = structure(c(1, 1, 1, 2, 2, 2, 3, 3, 3), format.stata = "%9.0g"), 
    year = structure(c(2005, 2006, 2010, 2002, 2005, 2006, 2006, 
    2009, 2010), format.stata = "%9.0g"), age = structure(c(50, 
    51, 55, 38, 41, 42, 30, 38, 39), format.stata = "%9.0g")), row.names = c(NA, 
-9L), class = c("tbl_df", "tbl", "data.frame"))

【问题讨论】:

    标签: r dplyr hierarchical-data panel-data


    【解决方案1】:

    我们可以使用diff

    library(dplyr)
    df %>%
        group_by(id) %>% 
        filter(!all(diff(year) == diff(age)))
    

    -输出

    # A tibble: 3 x 3
    # Groups:   id [1]
    #     id  year   age
    #  <dbl> <dbl> <dbl>
    #1     3  2006    30
    #2     3  2009    38
    #3     3  2010    39
    

    【讨论】:

      【解决方案2】:

      您可以过滤掉yearage 中的更改不同步的id

      library(dplyr)
      
      df %>%
        group_by(id) %>%
        filter(!all(year - min(year) == age - min(age))) -> unreasonable_data
      
      unreasonable_data
      
      #     id  year   age
      #  <dbl> <dbl> <dbl>
      #1     3  2006    30
      #2     3  2009    38
      #3     3  2010    39
      

      同样的逻辑也可以使用lag来实现。

      df %>%
        group_by(id) %>%
        filter(!all(year - lag(year) == age - lag(age))) -> unreasonable_data
      

      【讨论】:

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