2016-03-08 63 views
0

元件I具有两个元素:R:选择从列表

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

我想从一个向量

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

我试图提取这些元素(dogcat或catddog)的任意组合:

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

但这给出了一个错误。

我会很感谢您的帮助,纠正上述情况。

+1

'L [grep的(贴(ID1,ID2,九月= “”),L)] L [grep的(酱(ID2,ID1,九月=“”),L)]' – HubertL

+2

简单的非正则表达式解决方案可以是'grepl(id1,L)&grepl(id2,L)'。如果效率很重要,您可以将'fixed = TRUE'添加到两者。 –

+0

我不明白,但显然'grepl(“(dog(cat)?)”,L)'礼貌http://stackoverflow.com/questions/1177081/mulitple-words-in-any-order -using-regex – thelatemail

回答

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"