我有一个包含 Id-year 观测值的数据集。我想比较2015年前后/2015年之后的变化。所以我需要所有公司在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 不符合我的需要。
最佳答案
使用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)])
关于r - 面板数据 : How to remove IDs with missing yearly information,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52444291/