[英]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:我想根据 df2 中的行删除 df1 中的行,它们必须匹配所有 3 个条件:
The output for my example should look like:我的示例中的 output 应如下所示:
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"))
I wonder if tidyverse
could be also used:我想知道是否也可以使用
tidyverse
:
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
With data.table
, we can use a non-equi join使用
data.table
,我们可以使用非等连接
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或者使用与
fuzzy_anti_join
相同的方法,如本文所示
You can use fuzzy_anti_join
from fuzzyjoin
package:您可以使用来自
fuzzy_anti_join
fuzzyjoin
的fuzzy_anti_join:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.