R:从列表中选择元素

R:从列表中选择元素,r,R,我有两个要素: id1 <- "dog" id2 <- "cat" 但这是一个错误 如果您能帮助我更正上述错误,我将不胜感激。错误是由于括号放错了位置,因此您的代码中的这些细微变化将起作用 L[grep(paste(id1,id2,sep=""), L)] # character(0) L[grep(paste(id2,id1,sep=""), L)] # [1] "catdog" 或者,这是一个正则表达式一行: L[grep(paste0(id2, id1, "|", id1,

我有两个要素:

id1 <- "dog"
id2 <- "cat"
但这是一个错误


如果您能帮助我更正上述错误,我将不胜感激。

错误是由于括号放错了位置,因此您的代码中的这些细微变化将起作用

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"

x错误是由于括号放错了位置,因此代码中的这些细微变化将起作用

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"

x
L[grep(粘贴(id1,id2,sep=“”),L)]L[grep(粘贴(id2,id1,sep=“”),L)]
一个简单的非正则表达式解决方案可以是
grepl(id1,L)&grepl(id2,L)
。如果效率很重要的话,你可以将
fixed=TRUE
添加到两者中。我不明白,但显然
grepl((狗(猫)),L
的工作原理是模式匹配
dogcat
,但也
dog
,如:
grepl((狗(猫)),“dog”)
L[grep(粘贴(id1,id2,sep=”),L)]L[grep(粘贴(id2,id1,sep=)一个简单的非正则表达式解决方案可以是
grepl(id1,L)和grepl(id2,L)
。如果效率很重要,你可以将
fixed=TRUE
添加到两者中。我不明白这一点,但显然
grepl((狗(猫)“),L)
的工作原理是模式匹配
dogcat
,但也
dog
,如:
grepl((狗(猫)“,“dog”)