file1中有与file2中的部分字符串相匹配的字符串。我想从file2中筛选出与file1中的字符串部分匹配的字符串。请看我的尝试。不确定如何以这种方式定义子字符串匹配。
file1:
V1
species1
species121
species14341file2
V1
genus1|species1|strain1
genus1|species121|strain1
genus1|species1442|strain1
genus1|species4242|strain1
genus1|species4131|strain1我的尝试:
file1[!file1$V1 %in% file2$V1]发布于 2022-05-09 11:11:16
您不能以这种方式在R中使用%in%运算符,它用于确定向量的元素是否位于另一个向量中,而不像Python中的in那样可以用于匹配子字符串:请看以下内容:
"species1" %in% "genus1|species1|strain1" # FALSE
"species1" %in% c("genus1", "species1", "strain1") # TRUE但是,您可以为此使用grepl ( l表示逻辑,即返回TRUE或FALSE)。
grepl("species1", "genus1|species1|strain1") # TRUE这里还有一个额外的复杂性,因为您不能将grepl与向量一起使用,因为它只会比较第一个值:
grepl(file1$V1, "genus1|species1|strain1")
[1] TRUE
Warning message:
In grepl(file1$V1, "genus1|species1|strain1") :
argument 'pattern' has length > 1 and only the first element will be used以上简单地告诉您,file1$V1的第一个元素在"genus1|species1|strain1"中。
此外,您希望将file1$V1中的每个元素与整个字符串向量进行比较,而不仅仅是一个字符串。这是可以的,但是您将得到一个与第二个向量长度相同的向量作为输出:
grepl("species1", file2$V1)
[1] TRUE TRUE TRUE FALSE FALSE我们可以看到这些any()是否匹配。当您用tidyverse标记您的问题时,下面是一个dplyr解决方案:
library(dplyr)
file1 |>
rowwise() |> # This makes sure you only pass one element at a time to `grepl`
mutate(
in_v2 = any(grepl(V1, file2$V1))
) |>
filter(!in_v2)
# A tibble: 1 x 2
# Rowwise:
# V1 in_v2
# <chr> <lgl>
# 1 species14341 FALSE发布于 2022-05-09 11:25:33
获取所需内容的一种方法是使用grepl函数。因此,您可以运行以下代码:
# Load library
library(qdapRegex)
# Extract the names of file2$V1 you are interested in (those between | |)
v <- unlist(rm_between(file2$V1, "|", "|", extract = T))
# Which of theese elements are in file1$V1?
elem.are <- which(v %in% file1$V1)
# Delete the elements in elem.are
file2$V1[-elem.are]v我们保存了我们感兴趣的file2$V1的名称(那些在v之间的名称)然后,我们将file1$V1中出现的名称的位置保存在
最后,我们使用file2$V1[-elem.are]省略了这些元素。
https://stackoverflow.com/questions/72170763
复制相似问题