删除R中仅相差一列的特定行

问题描述


我创建了一个数据框,每个国家和年份应该有一个观测值。我有一个二进制变量(V1),它为一年和国家/地区同时提供(0和1)。结果如下表:

ID  
132     1 58 15 15 2014    Australia       Yes
133     0 58 15 15 2014    Australia       Yes
134     0 58 15 15 2015    Australia       Yes
135     0 58 15 15 2016    Australia       Yes
136     0 58 15 15 2017    Australia       Yes
137     1 58 15 15 2017    Australia       Yes
138     1 58 15 15 2018    Australia       Yes
139     0 58 15 15 2018    Australia       Yes
140     0 58 15 15 2019    Australia       Yes
141     0 57 15 15 2020    Australia       Yes

对于在同一年和某个国家/地区有多个观测值的情况,我只想保留那些V1变量的值为1的观测值。

解决方法

如果组中的行数是1或country,则可以为yearV1 == 1中的每一个选择行。

library(dplyr)
df %>% group_by(country,year) %>% filter(n() == 1 | V1 == 1)

data.table中的等效项是:

library(data.table)
setDT(df)[,.SD[.N == 1 | V1 == 1],.(country,year)]