0

I have two dataframes which share some matching coordinates. I want to find the location in xygrid of the rows that match in the two dataframes.

xygrid <- data.frame("x" = c(-175, -165, -155, -145, -135, -125, -115), "y" = c(85, 85, 85, 85, 85, 85, 85))

xygrid2 <- data.frame("x" = c(-165, -145), "y" = c(85, 85))

> xygrid
     x  y
1 -175 85
2 -165 85
3 -155 85
4 -145 85
5 -135 85
6 -125 85
7 -115 85

> xygrid2
     x  y
1 -165 85
2 -145 85

#Ideal output
> output
[1] FALSE  TRUE FALSE  TRUE FALSE FALSE FALSE

#So that I can extract the location
>   xygrid[output,]
     x  y
2 -165 85
4 -145 85

patch105
  • 29
  • 6
  • Is it important that you know the indices of the matching rows (2, 4), or is it sufficient just to extract them? If the latter you could use `dplyr::inner_join(xygrid, xygrid2)`, or `merge`. – neilfws Mar 24 '21 at 23:38
  • I need to know the indices - otherwise I would have gone for one of those options yes! :) – patch105 Mar 24 '21 at 23:45
  • [The accepted, or the second (higher voted) answer here](https://stackoverflow.com/questions/6880450/match-two-columns-with-two-other-columns) should help. – neilfws Mar 25 '21 at 00:08
  • Thanks for the suggestion. The accepted answer won't work in my case because my actual dataset will make far too large a matrix, and the second answer appears to only work when the vectors are the same length. – patch105 Mar 25 '21 at 00:40

2 Answers2

0

An admittedly simple answer:

library(dplyr)
xygrid %>% 
  left_join(xygrid2 %>% mutate(output = TRUE)) %>%
  mutate(output = ifelse(is.na(output), FALSE, output))

Add %>% pull(output) at the end if what you want is the vector form.

Hong
  • 574
  • 3
  • 10
0

paste the columns and find them in other dataframe using %in%

do.call(paste, c(xygrid, sep = '-')) %in% do.call(paste, c(xygrid2, sep = '-'))
#[1] FALSE  TRUE FALSE  TRUE FALSE FALSE FALSE
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213