Note that there are some explanatory texts on larger screens.

plurals
  1. POAvoid for loop in string replacement?
    text
    copied!<p>I've got data, a character vector (eventually I'll collapse it, so I don't care if it stays a vector or if it's treated as a single string), a vector of patterns, and a vector of replacements. I want each pattern in the data to be replaced by its respective replacement. I got it done with a <code>stringr</code> and a for loop, but is there a more R-like way to do it?</p> <pre><code>require(stringr) start_string &lt;- sample(letters[1:10], 10) my_pattern &lt;- c("a", "b", "c", "z") my_replacement &lt;- c("[this was an a]", "[this was a b]", "[this was a c]", "[no z!]") str_replace(start_string, pattern = my_pattern, replacement = my_replacement) # bad lengths, doesn't work str_replace(paste0(start_string, collapse = ""), pattern = my_pattern, replacement = my_replacement) # vector output, not what I want in this case my_result &lt;- start_string for (i in 1:length(my_pattern)) { my_result &lt;- str_replace(my_result, pattern = my_pattern[i], replacement = my_replacement[i]) } &gt; my_result [1] "[this was a c]" "[this was an a]" "e" "g" "h" "[this was a b]" [7] "d" "j" "f" "i" # This is what I want, but is there a better way? </code></pre> <p>In my case, I know each pattern will occur at most once, but not every pattern will occur. I know I could use <code>str_replace_all</code> if patterns might occur more than once; I hope a solution would also provide that option. I'd also like a solution that uses <code>my_pattern</code> and <code>my_replacement</code> so that it could be part of a function with those vectors as arguments.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload