[英]Merging datasets where the key is on the column of one dataset and row of another in R
[英]Two datasets: How to check if the values of a column of a dataset are contained in another column of another dataset in R?
我有兩個數據集data1和data2。 需要注意的是,我的data1包含300行,data2包含5000行。 兩個數據集都有一個名為 x2 的列(如上所示)。 data2 的 x2 列包含 5000 個汽車名稱值,而 data1 的 x2 列僅包含 300 個汽車名稱。
如何檢查data1的x2是否包含在data1的x2中?
data1 <- data.frame(x1 = c(1, 3, 7, 7, 4, 7),
x2 = c("a 1-metha (akD)", "methal methal", "methy", "3-[3-(methy)prox",
"3-carbon (C:H)", "z"),
x3 = 10:15)
data2 <- data.frame(x1 = c(1, 3, 7, 7, 4, 7),
x2 = c("a 1-metha (akD)|a 1-metha akaikedenioyl|a 1-m(akD)", "methal methal|X.methal methal|methal (22)", "methy", "3-[3-(methy)prox",
"3-carbon (C:H)", "y"),
x3 = 20:25)
我剛開始使用 R 語言。 但我嘗試使用 grep function。 我嘗試自動化,以避免在價值之后做它。
matchedValue <- grep(str_extract(data1$x1[1], "([[:alnum:][:punct:][:blank:]]+)"),
str_extract(data2$x2, "([[:alnum:][:punct:][:blank:]]+)"),
ignore.case = T)
我想知道例如 1-metha (akD)(請參閱 data1 的 x2 列)是否也存在於 data2 的 x2 中,我想為所有 300 行 data1 自動執行此操作。
請問我該怎么做?
library(tidyverse)
data1 %>%
mutate(in_data2 = x2 %in% str_extract(data2$x2, "^[^\\|]*"))
# A tibble: 6 × 4
x1 x2 x3 in_data2
<dbl> <chr> <int> <lgl>
1 1 a 1-metha (akD) 10 TRUE
2 3 methal methal 11 TRUE
3 7 methy 12 TRUE
4 7 3-[3-(methy)prox 13 TRUE
5 4 3-carbon (C:H) 14 TRUE
6 7 z 15 FALSE
我們可以使用str_detect
和fixed()
,參見https://cran.r-project.org/web/packages/stringr/vignettes/stringr.html#fixed-matches
library(dplyr)
library(stringr)
data1 %>%
mutate(check = str_detect(x2, fixed(data2$x2)))
x1 x2 x3 check
1 1 a 1-metha (akD) 10 FALSE
2 3 methal methal 11 FALSE
3 7 methy 12 TRUE
4 7 3-[3-(methy)prox 13 TRUE
5 4 3-carbon (C:H) 14 TRUE
6 7 z 15 FALSE
您可以在使用 sapply 返回的矩陣上使用 colSums 來檢查 data1 的每一行與 data2 的整個列。
data1$isin <- (colSums(sapply(data1$x2, \(x) grepl(x, data2$x2, fixed = T))) > 0)
x1 x2 x3 isin
1 1 a 1-metha (akD) 10 TRUE
2 3 methal methal 11 TRUE
3 7 methy 12 TRUE
4 7 3-[3-(methy)prox 13 TRUE
5 4 3-carbon (C:H) 14 TRUE
6 7 z 15 FALSE
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.