0

I am trying to replace the hyphen - in a vector with a period ..

> 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

The following code

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

generates the following error:

> 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

Any ideas? I have tried so many things and combinations but the coercing atomic vector message seems to reoccur

henhesu
  • 756
  • 4
  • 9
OJH
  • 49
  • 7

1 Answers1

0

Can you try utilizing an escape since "." is used to match any character when matching patterns with regular expressions? To create the regular expression, you need to use "\\."

str_replace_all(samples_149_vector, "-", "\\.")
Eric
  • 2,699
  • 5
  • 17
  • Replacements are taken literally--unless you're using capturing groups you don't need to escape special characters, e.g., `stringr::str_replace_all("a---s-s-s-a", "-", ".")` works fine. (Matching `.` in the `pattern`, of course, would require escaping as you've shown.) Which means the problem is probably OP's input data structure. – Gregor Thomas May 20 '20 at 13:44