Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用“查找字符向量的元素”+&引用;在R_R - Fatal编程技术网

使用“查找字符向量的元素”+&引用;在R

使用“查找字符向量的元素”+&引用;在R,r,R,我想获得包含“+”的字符向量的所有元素的索引 c(“A+B”、“c”)应输出1 c(“A+B”、“c+D”)应该输出c(1,2) c(“A”、“B”)应输出整数(0) 我尝试过使用grep(pattern=“+”,x),但不管x是什么,它都会返回整数(0)。我也尝试过使用grep(pattern=“+”,x),但无论x是什么,它都会沿着(x)返回seq_。我怀疑这与+是一个特殊字符有关,但我不确定如何解决这个问题。+是正则表达式中的一个特殊字符,需要使用\对其进行转义 我们可以使用grep来

我想获得包含“+”的字符向量的所有元素的索引

  • c(“A+B”、“c”)应输出1
  • c(“A+B”、“c+D”)应该输出c(1,2)
  • c(“A”、“B”)应输出整数(0)

我尝试过使用grep(pattern=“+”,x),但不管x是什么,它都会返回整数(0)。我也尝试过使用grep(pattern=“+”,x),但无论x是什么,它都会沿着(x)返回seq_。我怀疑这与+是一个特殊字符有关,但我不确定如何解决这个问题。

+
是正则表达式中的一个特殊字符,需要使用
\
对其进行转义

我们可以使用
grep
来获得模式匹配的索引

grep('\\+', c("A + B", "C"))
#[1] 1
grep('\\+', c("A + B", "C + D"))
#[1] 1 2
grep('\\+', c("A", "B")) 
#integer(0)

我们还可以使用返回布尔值的
grepl
,然后将其包装在
中,以获得索引

grepl('\\+', c("A + B", "C"))
#[1]  TRUE FALSE

which(grepl('\\+', c("A + B", "C")))
#[1] 1

也许您需要做的只是在
grep
中将
fixed
选项打开为
TRUE
,即

> grep('+', c("A + B", "C"), fixed = TRUE)
[1] 1
> 
> grep('+', c("A + B", "C + D"), fixed = TRUE)
[1] 1 2
> 
> grep('+', c("A", "B"), fixed = TRUE)
integer(0)