【问题标题】:replacing a term in vector using str_replace_all function R [duplicate]使用str_replace_all函数R替换向量中的一个术语[重复]
【发布时间】:2020-09-06 21:11:56
【问题描述】:

我正在尝试用句点 . 替换向量中的连字符 -

> samples_149_vector 
$Patient.ID
  [1] MB-0020 MB-0100 MB-0115 MB-0158 MB-0164 MB-0174 MB-0179 MB-0206
  [9] MB-0214 MB-0238 MB-0259 MB-0269 MB-0278 MB-0333 MB-0347 MB-0352
 [17] MB-0372 MB-0396 MB-0399 MB-0400 MB-0401 MB-0420 MB-0424 MB-0446
 [25] MB-0464 MB-0476 MB-0481 MB-0489 MB-0494 MB-0495 MB-0500 MB-0502

以下代码

library(stringr)
str_replace_all(samples_149_vector, "-", ".")

产生以下错误:

> str_replace_all(samples_149_vector, "-", ".")
[1] "1:149"                                                           
[2] "function (length = 0) \n.Internal(vector(\"character\", length))"
Warning message:
In stri_replace_all_regex(string, pattern, fix_replacement(replacement),  :
  argument is not an atomic vector; coercing

有什么想法吗?我尝试了很多东西和组合,但强制原子向量消息似乎再次出现

【问题讨论】:

  • samples_149_vector是什么类型的对象?
  • 您需要escape\\. 或使用字符类,尽管我无法重现。你能用dput添加数据吗?
  • @NelsonGon,您能否参考我的代码澄清一下?提前致谢。
  • 您可以使用 dput(df) 将数据添加到您的问题中,因此我们使用的是相同的数据。请编辑以添加该格式的数据

标签: r vector replace str-replace


【解决方案1】:

您可以尝试使用转义,因为"." 用于在使用正则表达式匹配模式时匹配任何字符?要创建正则表达式,需要使用"\\."

str_replace_all(samples_149_vector, "-", "\\.")

【讨论】:

  • 按字面意思进行替换——除非您使用捕获组,否则您不需要转义特殊字符,例如,stringr::str_replace_all("a---s-s-s-a", "-", ".") 可以正常工作。 (当然,在pattern 中匹配. 需要转义,如您所示。)这意味着问题可能出在OP 的输入数据结构上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-22
相关资源
最近更新 更多