【发布时间】:2020-05-15 12:14:14
【问题描述】:
我只想选择我数据框中所有年份的 ID,从 2013 年到 2016 年(所以四次)。在这种情况下,只剩下四行的 ID(面板数据,每个 ID 每年都有 1 行)。我已经确保我的数据框仅涵盖我需要的年份(2013 年、2014 年、2015 年和 2016 年),但我想排除数据框中少于 4 年/行的 ID。
这是我的数据框的结构:
tibble [909,587 x 26] (S3: tbl_df/tbl/data.frame)
$ ID : num [1:909587] 12 12 12 12 16 16 16 16...
$ Gender : num [1:909587] 2 2 2 2 1 1 1 1 1 1 ...
..- attr(*, "format.spss")= chr "F10.0"
$ Year : chr [1:909587] "2016" "2013" "2014" "2015" ...
..- attr(*, "format.spss")= chr "F9.3"
$ Size : num [1:909587] 1983 1999 1951 1976 902 ...
$ Costs : num [1:909587] 2957.47 0 0.34 1041.67 0 ...
$ Urbanisation : num [1:909587] 2 3 3 2 3 3 2 2 2 3 ...
$ Age : num [1:909587] 92 89 90 91 82 83 22 23 24 65 ...
我怎样才能做到这一点?
谢谢!
【问题讨论】:
-
请阅读如何提供good example。仅提供数据结构并没有多大帮助。考虑使用
dput。也就是说,这可能工作:df %>% group_by(ID) %>% filter(n_distinct(Year) >= 4) -
谢谢 Jason,我希望结构足够。好消息;你的代码有效!现在我只有4年的身份证。谢谢!
-
嗨杰森,谢谢你这样做!我刚刚发现代码“错过”了几年/行/ID。根据 lenght(unique(df$ID) * 4 rows.. 知道怎么做吗?
标签: r dataframe dplyr row tidyverse