How to find common rows between two data frames in R?

I would like to create a new data frame that includes only regular rows from two separate data.frames. Example:

data.frame 1

1 id300
2 id2345
3 id5456
4 id33
5 id45
6 id54

data.frame2

1 id832
2 id300
3 id1000
4 id45
5 id984
6 id5456
7 id888

So, I want my result to be:

1 id300
2 id45
3 id5456

any suggestion please?

+4
source share
5 answers
common <- intersect(data.frame1$col, data.frame2$col)  
data.frame1[common,] # give you common rows in data frame 1  
data.frame2[common,] # give you common rows in data frame 2
+4
source

The corresponding function is dplyrhere inner_join(returns all rows from df xthat have a match in df y.)

library(dplyr)
inner_join(df1, df2)

      V1
1  id300
2 id5456
3   id45

Note: rows are returned in the order in which they are in df1. If you are done inner_join(df2, df1), id45will appear earlier id5456.

+7
source

merge

new_data_frame <- merge(data.frame1, data.frame2)

, , . , , by.x = "nameCol1" by.y = "nameCol2", nameCol - .


, . :

>a  #Data frame 1
      c1 c2
1  id300  6
2 id2345  5
3 id5456  4
4   id33  3
5   id45  2
6   id54  1

> b #Data frame 2
     a  f
1  asd 12
2 id33 10
3 id45  8
4 id54  6

, . :

> merge(a,b, by.x = "c1", by.y = "a")

    c1 c2  f
1 id33  3 10
2 id45  2  8
3 id54  1  6

- , .

+2

fintersect data.table data.frame data.table

library(data.table)
fintersect(setDT(df1), setDT(df2))
#       v1
#1:  id300
#2:   id45
#3: id5456

df1 <- structure(list(v1 = c("id300", "id2345", "id5456", "id33", "id45", 
"id54")), .Names = "v1", class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))

df2 <- structure(list(v1 = c("id832", "id300", "id1000", "id45", "id984", 
"id5456", "id888")), .Names = "v1", class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7"))
+1

To achieve this, you must assign row names in both data frames, and then process them using the intersection in R. This can be achieved using the following command:

intersect(dataframe.1$V1,dataframe.2$V2)
0
source

Source: https://habr.com/ru/post/1610060/


All Articles