Sarah
Sarah

Reputation: 61

Delete rows from a data frame in R based on column values in another data frame

I have two data frames as follows:

df1 <- data.frame(fruit=c("apple", "blackberry", "orange", "pear", "grape"), 
color=c("black", "purple", "blue", "green", "red"), 
quantity1=c(1120, 7600, 21409, 120498, 25345), 
quantity2=c(1200, 7898, 21500, 140985, 27098), 
taste=c("sweet", "bitter", "sour", "salty", "spicy"))

df2 <- data.frame(fruit=c("apple", "orange", "pear"), 
color=c("black", "yellow", "green"), 
quantity=c(1145, 65094, 120500))

I would like to delete rows in df1 based on rows in df2, they must match all 3 conditions:

  1. The fruit name must match
  2. The color must match
  3. The quantity in df2 must be a value in between the two quantities in df1

The output for my example should look like:

df3 <- data.frame(fruit=c("blackberry", "orange", "grape"), 
color=c("purple", "blue", "red"), 
quantity1=c(7600, 21409, 25345), 
quantity2=c(21500, 7898, 27098), 
taste=c("bitter", "sour", "spicy"))

Upvotes: 1

Views: 125

Answers (3)

Zhiqiang Wang
Zhiqiang Wang

Reputation: 6769

I wonder if tidyverse could be also used:

library(tidyverse)
df1 %>%
  left_join(df2, by = c("fruit", "color")) %>%
  filter(is.na(quantity) | quantity <= quantity1 | quantity >= quantity2)
  
#>        fruit  color quantity1 quantity2  taste quantity
#> 1 blackberry purple      7600      7898 bitter       NA
#> 2     orange   blue     21409     21500   sour       NA
#> 3      grape    red     25345     27098  spicy       NA

Upvotes: 1

akrun
akrun

Reputation: 887851

With data.table, we can use a non-equi join

library(data.table)
setDT(df1)[!df2, on = .(fruit, color, quantity1 <= quantity,
           quantity2 >= quantity)]
#        fruit  color quantity1 quantity2  taste
#1: blackberry purple      7600      7898 bitter
#2:     orange   blue     21409     21500   sour
#3:      grape    red     25345     27098  spicy

Or using the same methodology with fuzzy_anti_join as showed in this post

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389235

You can use fuzzy_anti_join from fuzzyjoin package :

fuzzyjoin::fuzzy_anti_join(df1, df2, 
     by = c('fruit', 'color','quantity1' = 'quantity', 'quantity2' = 'quantity'), 
     match_fun = list(`==`, `==`, `<=`, `>=`))

# A tibble: 3 x 5
#  fruit      color  quantity1 quantity2 taste 
#  <chr>      <chr>      <dbl>     <dbl> <chr> 
#1 blackberry purple      7600      7898 bitter
#2 orange     blue       21409     21500 sour  
#3 grape      red        25345     27098 spicy 

Upvotes: 0

Related Questions