【问题标题】:R: cannot grep() on "+" character?R:不能在“+”字符上使用 grep()?
【发布时间】:2014-02-09 20:37:49
【问题描述】:

这是我的数据:

> rep$strand
  [1] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  [58] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + +
  [115] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  [172] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
  [229] + + + + + + + + + + + + + + + + + + + +

为了将"+""-" 分开,我尝试运行以下命令。

grepl("-",rep$strand) #this gives me a list of TRUE/FALSE that seems correct
grepl("+",rep$strand) #this is all TRUE for some mysterious reason

我不明白为什么同样的grepl() 命令可以在"-" 上运行,但在"+" 上却不行。

【问题讨论】:

  • + 是一个正则表达式元字符。您需要将其转义以删除其“元性”。
  • ...用反斜杠完成。其中两个。
  • 或 grepl("+", "some + in here", fixed=TRUE)
  • 您可以在文档中找到有关正则表达式的更多详细信息:stat.ethz.ch/R-manual/R-devel/library/base/html/regex.html

标签: regex r grepl


【解决方案1】:

使用

grepl("\\+", rep$strand)

grepl("+", rep$strand, fixed = TRUE)

"+" == rep$strand

【讨论】:

  • +1 表示完整性,但对于第一个,使用^\\+$ 与其他两个等效是否更正确?
  • @BrodieG 前两个命令是等价的。我同意,可以在第一个命令中使用^\\+$ 使其等同于第三个命令。但是,第二个命令不能等同于第三个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-02
相关资源
最近更新 更多