[英]Merge two dataframes based on an exact match in one column and match within an error in another column in R
[英]inner join on two dataframes based on an exact match for one column and fuzzy match for two columns
我想對我的一列 (Product_date) 執行精確匹配,然后對 product_name 和 state_name 進行部分匹配或模糊匹配。
例如:
df1 <- data.frame(ID=c("P01", "P04", "P23"),
Product_name=c("Jewel", "Bronze", "Iron"),
Product_state=c("Kansas", "Illinois", "Florida"),
Product_date=c("2021-08-01", "2021-01-01", "2020-12-21"))
df2 <- data.frame(
Product_name=c("Jewel", "Bro", "Ir", "Uknw"),
Product_state=c("Kansasss", "IllI", "Flor_ida", "Cali2"),
Product_date=c("2021-08-01", "2021-01-01", "2020-12-21", "2020-09"),
Product_status=c("sold", "lost", "sold", "sold"))
desired_df <- data.frame(c("P01", "P04", "P23"),
Product_name=c("Jewel", "Bronze", "Iron"),
Product_state=c("Kansas", "Illinois", "Florida"),
Product_date=c("2021-08-01", "2021-01-01", "2020-12-21"),
Product_name=c("Je", "Bro", "Ir"),
Product_state=c("Kansasss", "IllI", "Flor_ida"),
Product_date=c("2021-08-01", "2021-01-01", "2020-12-21"),
Product_status=c("sold", "lost", "sold"))
僅出於說明目的,這就是我腦海中的代碼的樣子(但當然它不起作用)
matched <- df1 %>%
stringdist_inner_join(df2, by= c("Product_name", max_dist=2),
by= c("Product_stat", max_dist=4),
by = c("Product_date"))
一個可能的解決方案:
library(fuzzyjoin)
library(dplyr)
stringdist_join(df1, df2,
by = c("Product_name","Product_state"),
mode = "left",
ignore_case = FALSE,
method = "jw",
max_dist = 0.5) %>%
filter(Product_date.x == Product_date.y)
#> ID Product_name.x Product_state.x Product_date.x Product_name.y
#> 1 P01 Jewel Kansas 2021-08-01 Jewel
#> 2 P04 Bronze Illinois 2021-01-01 Bro
#> 3 P23 Iron Florida 2020-12-21 Ir
#> Product_state.y Product_date.y Product_status
#> 1 Kansasss 2021-08-01 sold
#> 2 IllI 2021-01-01 lost
#> 3 Flor_ida 2020-12-21 sold
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.