我有一个包含多个变量的数据框,我想知道如何对其进行子集操作,以便只包含第一个重复项。
>head(occurrence)
userId occurrence profile.birthday profile.gender postDate count
1 100469891698 6 47 Female 583 days 0
2 100469891698 6 47 Female 55 days 0
3 100469891698 6 47 Female 481 days 0
4 100469891698 6 47 Female 583 days 0
5 100469891698 6 47 Female 583 days 0
6 100469891698 6 47 Female 583 days 0
在这里您可以看到数据框。'occurrence'列计算了相同userId出现的次数。我尝试使用以下代码来删除重复项:
occurrence <- occurrence[!duplicated(occurrence$userId),]
然而,这种方式会删除“随机”的重复数据。我想保留发表日期最早的数据。因此,例如第一行应该像这样:
userId occurrence profile.birthday profile.gender postDate count
1 100469891698 6 47 Female 583 days 0
感谢您的帮助!
duplicated
函数将除第一个以外的所有出现都标记为TRUE
(不随机)。但是,您的数据可能没有按postDate
倒序排列,因此您需要在调用之前对其进行排序或使用按postDate
分组并仅保留每个userId
的一行的替代方法(您可以在 SO Q&A 中找到执行此操作的代码示例)。 - Cath