Home > Enterprise >  R finding the rows that exist within another dataframe
R finding the rows that exist within another dataframe

Time:06-28

I have two dataframes A and B:

A

     x          y
1   0.0  0.0000000
2   0.5  0.8000000
3  -0.5  0.8000000
4  -1.0  0.0000000
5  -0.5 -0.8000000
6   0.5 -0.8000000
7   1.0  0.0000000
8   1.5  0.8000000

B

     x          y
1  -1.0  0.0000000
2   0.5 -0.8000000
3   3.0  0.0000000

I want to extract just the rows in A that exist in B so that the final result will be:

     x          y
4  -1.0  0.0000000
6   0.5 -0.8000000

How should I go about doing this?

CodePudding user response:

Use the intersect function

# Data frame 1 
data_x <- data.frame(x1 = c(2, 3, 4),     
                     x2 = c(1, 1, 1)) 
    
# Data frame 2 
data_y <- data.frame(y1 = c(2, 3, 4),        
                     y2 = c(2, 2, 2)) 
    
# Intersection of two data frames 
data_z <- intersect(data_x, data_y)   
    
print(data_z)    

CodePudding user response:

try this enter link description here

CodePudding user response:

Another option is using subset:

subset(B, (x %in% A$x))

Output:

     x    y
1 -1.0  0.0
2  0.5 -0.8

Data

A <- read.table(text = "     x          y
1   0.0  0.0000000
2   0.5  0.8000000
3  -0.5  0.8000000
4  -1.0  0.0000000
5  -0.5 -0.8000000
6   0.5 -0.8000000
7   1.0  0.0000000
8   1.5  0.8000000", header = TRUE)

B <- read.table(text = "     x          y
1  -1.0  0.0000000
2   0.5 -0.8000000
3   3.0  0.0000000", header = TRUE)
  •  Tags:  
  • r
  • Related