我使用一个包含 16 个变量和 80.000 个观察值的数据集。
变量“syear”描述了观察的年份(2008、2012、2016)。 变量“pid”描述了唯一的人 ID。
正如您在屏幕截图中看到的,人们可能只参与了一年或两年。我只想保留参与所有三年的人的观察。在屏幕截图中,这将是 pid 901 和 1501。
如何按此条件过滤我的数据集?
答案 0 :(得分:0)
你可以试试这个:
library(tidyverse)
df <- tribble(
~syear, ~pid,
2008,201,
2008,203,
2008,602,
2012,602,
2008,604,
2008,901,
2012,901,
2016,901,
2008,1501,
2012,1501,
2016,1501
)
df %>%
group_by(pid) %>%
mutate(cnt = n()) %>%
filter(cnt == 3)
# alternatively, the cnt column can be dropped
df %>%
group_by(pid) %>%
mutate(cnt = n()) %>%
filter(cnt == 3) %>%
select(-cnt)
答案 1 :(得分:0)
为了简化 nyk 的回答,您也可以这样做:
library(dplyr)
library(conflicted)
conflict_prefer("filter", "dplyr")
#> [conflicted] Will prefer dplyr::filter over any other package
tibble(
year = c(2001, 2002, 2003, 2001, 2003, 2002, 2003),
pid = c(1, 1, 1, 2, 2, 3, 3)
) %>%
group_by(pid) %>%
filter(n() == 3)
#> # A tibble: 3 x 2
#> # Groups: pid [1]
#> year pid
#> <dbl> <dbl>
#> 1 2001 1
#> 2 2002 1
#> 3 2003 1
由 reprex package (v0.3.0) 于 2021 年 1 月 5 日创建
因此您不必创建 cnt 作为中间变量。根据您之后想做什么,您可以调用 ungroup()
。