user1775563
user1775563

Reputation: 317

Remove all unique rows

I am trying to figure out how to remove all unique rows, from a data frame, but if it has a duplicate, I want that to stay in. For Example - I want all columns from this with col1 the same:

df<-data.frame(col1=c(rep("a",3),"b","c",rep("d",3)),col2=c("A","B","C",rep("A",3),"B","C"),col3=c(3,3,1,4,4,3,2,1))
df
  col1 col2 col3
1    a    A    3
2    a    B    3
3    a    C    1
4    b    A    4
5    c    A    4
6    d    A    3
7    d    B    2
8    d    C    1

subset(df,duplicated(col1))
  col1 col2 col3
2    a    B    3
3    a    C    1
7    d    B    2
8    d    C    1

But I want to have rows 1,2,3,6,7,8 since they all have the same col 1. How do I get 1 and 6 to be included? Or, conversely, how do I remove rows that do not have a duplicate?

Upvotes: 9

Views: 9025

Answers (3)

BrodieG
BrodieG

Reputation: 52637

You can do this by creating an index with ave:

df[as.logical(ave(1:nrow(df), df$col1, FUN=function(x) length(x) > 1)), ]

produces

  col1 col2 col3
1    a    A    3
2    a    B    3
3    a    C    1
6    d    A    3
7    d    B    2
8    d    C    1

Upvotes: 3

Matthew Plourde
Matthew Plourde

Reputation: 44614

Another option:

subset(df,duplicated(col1) | duplicated(col1, fromLast=TRUE))

Upvotes: 18

harkmug
harkmug

Reputation: 2785

Try:

> tdf <- table(df$col1)
a b c d 
3 1 1 3 

df[df$col1 %in% names(tdf)[tdf>1],]
> df
  col1 col2 col3
1    a    A    3
2    a    B    3
3    a    C    1
6    d    A    3
7    d    B    2
8    d    C    1

Upvotes: 6

Related Questions