Reputation: 149
I have two df (df1 and df2) in R each with one column each with the header Person. My real df:s are much longer but example like this :
df1:
Person
P1
P2
P5
P8
P11
df2:
Person
P1
P5
P7
P8
P12
I know want to create a new df with just the elements that are the same in both data frames, so in this example it would be:
newdf:
Person
P1
P5
P8
I think it should be a commando for this but I cant find one.
Upvotes: 0
Views: 102
Reputation: 887078
Another option is inner_join
from dplyr
library(dplyr)
inner_join(df1, df2)
# Person
#1 P1
#2 P5
#3 P8
If there are multiple datasets i.e. >2, one option is join_all
from plyr
after placing the datasets in a list
df3 <- data.frame(Person=c("P1", "P5"))
library(plyr)
join_all(list(df1, df2, df3), by='Person', type='inner')
# Person
#1 P1
#2 P5
You can change the type
argument according to the need.
Upvotes: 0
Reputation: 388962
You can try -
new_df <- as.data.frame(intersect(df1$Person, df2$Person))
Upvotes: 1