1

This is a simple stupid test put together to explain what was happening with my code. Why does replace simply spit back what is fed into it instead of actually replacing the content? It is because of this unexpected behavior that I am now using gsub instead.

Examples:

> replace(x="cat", "a", "o")
          a 
"cat"   "o" 

> gsub("a", "o", "cat")
[1] "cot"
undercovertek
  • 148
  • 1
  • 11
  • 2
    What does `?replace` tell you? It isn't a string substitution function. This question might help: https://stackoverflow.com/q/11811027/4996248 – John Coleman Sep 09 '17 at 14:07
  • help seems to agree with how I used it but I find that R help is often not written for novices: `replace replaces the values in x with indices given in list by those given in values. If necessary, the values in values are recycled.` Based on the writeup, I would expect output of `cot` or faulty output showing me how I misused the arguments, not what I am getting. – undercovertek Sep 09 '17 at 14:11
  • just checked the link in your comment. I see how it works now. I had thought you could pass in a single value because I thought I had used it before with dplyr but was probably misremembering. – undercovertek Sep 09 '17 at 14:18
  • `str(replace(x="cat", "a", "o"))` will show you what `replace` does here. I do find it surprising that it works that way. R isn't always intuitive. – John Coleman Sep 09 '17 at 14:20
  • If you really wanted to use `replace` then you would need to do it along these lines: `s <- strsplit("cat", "")[[1]]; paste(replace(s, s == "a", "o"), collapse = "")` – G. Grothendieck Sep 09 '17 at 14:34

0 Answers0