R:从列表中选择元素

时间:2016-03-08 23:40:33

标签: r grep

我有两个要素:

id1 <- "dog"
id2 <- "cat"

我想从矢量中提取这些元素(dogcat或catddog)的任意组合

L <- c("gdoaaa","gdobbb","gfoaaa","ghobbb","catdog")
L

我试过了:

L[grep(paste(id1,id2,sep="")),L]
L[grep(paste(id2,id1,sep="")),L]

但这会产生错误。

我很感谢你帮助纠正上述情况。

1 个答案:

答案 0 :(得分:2)

错误来自于错误的括号,因此您的代码上的这些微小变化将起作用。

L[grep(paste(id1,id2,sep=""), L)]
# character(0)
L[grep(paste(id2,id1,sep=""), L)]
# [1] "catdog"

或者这是一个正则表达式:

L[grep(paste0(id2, id1, "|", id1, id2), L)]
# [1] "catdog"

评论中的一些模式也会匹配dogcatt。为避免这种情况,您可以使用^$,如下所示:

x <- c("dogcat", "foo", "catdog", "ddogcatt")
x[grep(paste0("^", id2, id1, "|", id1, id2, "$"), x)]
# [1] "dogcat" "catdog"
相关问题