将 list1 的整个单元格与 list2 的所有单元格的开头匹配

Match the whole cell of list1 to beginning of all cells of list2

当前问题是的扩展。
从上一个问题我有一个代码:

list1<-list("q","w","e","r","t")
list2<-list("a","a","aq","c","f","g")

any(sapply(list1, grepl, list2))
# [1] TRUE

它将list1的每个单元格中的整个字符串一一匹配到list2中的字符串的任何部分每个细胞。如果有任何匹配,我会收到作为输出单曲 TRUE。现在我需要将其修改为在 list2 中只匹配每个单元格中字符串的开头。例如,如果我有

list1<-list("q","w","e","r","t")
list2<-list("a","a","aq","c","f","g")

list1<-list("q","w","e","r","t")
list2<-list("a","a","aqaa","c","f","g")

结果应该是FALSE。但如果我有:

list1<-list("q","w","e","r","t")
list2<-list("a","a","qa","c","f","g")

答案应该是TRUE

您也可以在此处使用锚点 regex。请注意,我正在更改您的原始输入,以便对其外观更具指导意义。

> list1<-list("q","w","e","r","t")
> list2<-list("a","a","aq","c","rs", "t")
> 
> lapply(list1, function(x) grepl(paste0("^", x, "$"), list2))
[[1]]
[1] FALSE FALSE FALSE FALSE FALSE FALSE

[[2]]
[1] FALSE FALSE FALSE FALSE FALSE FALSE

[[3]]
[1] FALSE FALSE FALSE FALSE FALSE FALSE

[[4]]
[1] FALSE FALSE FALSE FALSE FALSE FALSE

[[5]]
[1] FALSE FALSE FALSE FALSE FALSE  TRUE

请注意,这也适用于 sapply

编辑:提供更多细节

如果你使用 sapply

,你的结果会是这样的(没有 any
sapply(list1, function(x) grepl(paste0("^", x, "$"), list2))

      [,1]  [,2]  [,3]  [,4]  [,5]
[1,] FALSE FALSE FALSE FALSE FALSE
[2,] FALSE FALSE FALSE FALSE FALSE
[3,] FALSE FALSE FALSE FALSE FALSE
[4,] FALSE FALSE FALSE FALSE FALSE
[5,] FALSE FALSE FALSE FALSE FALSE
[6,] FALSE FALSE FALSE FALSE  TRUE

现在在 lapply 的原始输出上使用 anysapply 输出将如下所示:

lapply(lapply(list1, function(x) grepl(paste0("^", x, "$"), list2)), any)
[[1]]
[1] FALSE

[[2]]
[1] FALSE

[[3]]
[1] FALSE

[[4]]
[1] FALSE

[[5]]
[1] TRUE

sapply

any(sapply(list1, function(x) grepl(paste0("^", x, "$"), list2)))
[1] TRUE

但是如果你想 apply 从原始 lapply 代码输出,你可以使用:

sapply(lapply(list1, function(x) grepl(paste0("^", x, "$"), list2)), any)
[1] FALSE FALSE FALSE FALSE  TRUE

这取决于你想要的输出。

您可以使用与 startsWith 之前相同的方法。您只需要翻转列表顺序(请注意,它正在检查 list2 中的任何元素是否以 list1.

中的字母开头
list1<-list("q","w","e","r","t")
list2<-list("a","a","qa","c","f","g")

any(sapply(list2, startsWith, unlist(list1)))
[1] TRUE