0

I'm trying to get the coords common to two different dataframes (nodes and poly)removed from the nodes data frame. The code below works if the coordinates line up element-wise, but not otherwise.

v1 <- c(2, 2, 4)
v2 <- c(9, 2, 7)
nodes <- data.frame(v1, v2)

v3 <- c(4, 1, 2)
v4 <- c(3, 2, 2)
poly <- data.frame(v3, v4)

newnodes <- nodes[-which(nodes[,1:2] == poly[,1:2]), ]

How can I achieve this? Desired output for nodes is:

  v1 v2
   2  9
   4  7
hmnoidk
  • 545
  • 6
  • 20

2 Answers2

0

One easy way is dplyr::setdiff. This requires that the names of the columns match up, but we can do that on the fly:

dplyr::setdiff(nodes, setNames(poly, names(nodes)))
#   v1 v2
# 1  2  9
# 2  4  7

More verbosely, this operation is an anti-join:

dplyr::anti_join(nodes, poly, by = c("v1" = "v3", "v2" = "v4"))
  v1 v2
1  2  9
2  4  7

You can find more options at How to anti-join in R, though that question only uses a single column so some of the methods won't work so well for you.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
0

You can also create a new column of keyword by pasting two previous columns. This keyword helps you to find differences between two data frames:

nodes_k = data.frame(nodes, key = paste(nodes$v1, nodes$v2) )
poly_k = data.frame(poly, key = paste(poly$v3, poly$v4) )

nodes_k[ !(nodes_k$key %in% poly_k$key) , ][,1:2]
#   v1 v2
# 1  2  9
# 3  4  7
Ulises Rosas-Puchuri
  • 1,900
  • 10
  • 12