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
298 views
in Technique[技术] by (71.8m points)

r - 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?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Another option:

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

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

...