Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/79.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-为什么不';t grep返回多个索引?_R - Fatal编程技术网

R-为什么不';t grep返回多个索引?

R-为什么不';t grep返回多个索引?,r,R,对于此代码: > grep("abc","abcabcabc", value=FALSE) [1] 1 我想它会给出字符串中出现“abc”的所有索引。我做错什么了吗?我是否应该使用其他方法来查找字符串中所有出现的模式?使用gregexpr(): gregexpr("abc","abcabcabc") [[1]] [1] 1 4 7 attr(,"match.length") [1] 3 3 3 attr(,"useBytes") [1] TRUE 这表明在位置1、4和7有匹配项。每个匹

对于此代码:

> grep("abc","abcabcabc", value=FALSE)
[1] 1
我想它会给出字符串中出现“abc”的所有索引。我做错什么了吗?我是否应该使用其他方法来查找字符串中所有出现的模式?

使用
gregexpr()

gregexpr("abc","abcabcabc")
[[1]]
[1] 1 4 7
attr(,"match.length")
[1] 3 3 3
attr(,"useBytes")
[1] TRUE
这表明在位置1、4和7有匹配项。每个匹配的长度为3个字符


如果只想打印匹配的位置,而不想打印其他属性,请使用以下技巧:

x <- gregexpr("abc","abcabcabc")
lapply(x, c)
[[1]]
[1] 1 4 7
有关原因,请参见《财富》(185)


grep
仅返回找到匹配项的索引值

x <- c('a', 'b', 'aa', 'abc', 'bc')

grep('a', x)
# [1] 1 3 4

x谢谢。那么,如何只打印gregexpr输出的“14 7”部分呢?我想有人会提到《财富》(185)
。另请参见
stringr::str\u locale\u all
library(fortunes)
fortune(185)

I don't like to see the use of c() for its side effects. In this case Marc's
as.vector seems to me to be self-explanatory, and that is a virtue in programming
that is too often undervalued.
   -- Brian D. Ripley (on how to convert a matrix into a vector)
      R-help (March 2007)
x <- c('a', 'b', 'aa', 'abc', 'bc')

grep('a', x)
# [1] 1 3 4