Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

r - Remove all duplicates except last instance

So I have a dataset in R with the following layout as an example:

ID Date Tally
1 2/1/2011 1
2 2/1/2011 2
3 2/1/2011 3
1 2/1/2011 4
2 2/1/2011 5
1 2/1/2011 6
3 2/1/2011 7
4 2/1/2011 8
2 2/1/2011 9

I want to remove all instances except the LAST instance of the post id. Right now everything I can find online, and functions I am using is removing everything except the FIRST instance.

So my new data frame would look like:

ID Date Tally
1 2/1/2011 6
3 2/1/2011 7
4 2/1/2011 8
2 2/1/2011 9

How do I do this? Right now I am only able to keep the first instance. I want it to do the opposite? Any help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Wouldn't this just be the standard case for using the 'fromLast' parameter to duplicated?

 dat[ !duplicated(dat[, c("ID", "Date")], fromLast=T),]
#---------
  ID     Date Tally
6  1 2/1/2011     6
7  3 2/1/2011     7
8  4 2/1/2011     8
9  2 2/1/2011     9

Your example was not rich enough to tell whether you needed the "Date" column in the test fro duplication, so perhaps you could simplify. I'm leaving it in to illustrate that duplicated has a data.frame method. I prefer !duplicated to unique because it allows easy access to the set complement if you are comparing groups.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...