在R中选择唯一的工作场所id组合



考虑我的数据集的以下子集,该子集由大约22000个人组成。

df<-data.frame( c("Den Haag", "Den Haag", "Den Haag", "Rotterdam", "Den Haag",
"Den Haag", "Amsterdam"),
c("R007", "R007", "R008", "R008", "R008", "R009", "R009"), 
c(20130101, 20140101 ,20130101, 20130101, 20140101, 20130101, 20140101), 
c(40000,42000,22000,20000,38000,10000, 15000))
colnames(df)<-c("Gemeente", "id", "Date", "income")
df$Date<-as.character(df$Date)
df$Date<-as.Date(df$Date, "%Y%m%d")

在上述数据集中;Gemeente";表示人们工作的地方,id变量是人。我的目标是在我的样本中删除在一个以上工作场所工作的所有观察结果。他们是在随后的几年(R009(还是在同一年(R008(在不同的工作场所工作并不重要。更确切地说,我也想在2013年和2014年都放弃R008,因为这个人2013年在两个市镇工作。因此,在这种情况下,这意味着我将放弃观测值R008和R009,只剩下R007。

我以为我可以用下面的方式来做,但我对unique命令做了一些错误的操作,它选择了样本中的所有唯一id,而我只想选择R007。有人知道我应该使用什么命令吗?

#Select unique rows of observations based on muncipality and id
library(dplyr)
#Select all unique combinations of Municipality and ids
test<-distinct(df, Gemeente, id))
#Select the number of unique ids (i.e. drop the ids that work at more than one place in our dataset)
#But here I only want to select id R007, but with this command I select all three. So this is where I go wrong.
test2<-as.data.frame(unique(test$id))
colnames(test2)[1]<-"id"
test2$nr<-1
#Use left_join to the initial dataset. 
dffinal<-left_join(df, test2, by = "id")
dffinal<-subset(dffinal, nr ==1)

我感谢你的帮助。

这行吗:

library(dplyr)
df %>% group_by(id) %>% filter(length(unique(Gemeente)) == 1)
# A tibble: 2 x 4
# Groups:   id [1]
Gemeente id    Date       income
<fct>    <fct> <date>      <dbl>
1 Den Haag R007  2013-01-01  40000
2 Den Haag R007  2014-01-01  42000
> 

最新更新