Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'll bet there's another way to do this, but my first thought was <strong>gsubfn</strong>:</p> <pre><code>my_repl &lt;- function(x){ switch(x,a = "[this was an a]", b = "[this was a b]", c = "[this was a c]", z = "[this was a z]") } library(gsubfn) start_string &lt;- sample(letters[1:10], 10) gsubfn("a|b|c|z",my_repl,x = start_string) </code></pre> <p>If the patterns you are search for a acceptably valid names for list elements, this will also work:</p> <pre><code>names(my_replacement) &lt;- my_pattern gsubfn("a|b|c|z",as.list(my_replacement),start_string) </code></pre> <p><strong>Edit</strong></p> <p>But frankly, if I really had to do this a lot in my own code, I would probably just do the <code>for</code> loop thing, wrapped in a function. Here's a simple version using <code>sub</code> and <code>gsub</code> rather than the functions from <strong>stringr</strong>:</p> <pre><code>vsub &lt;- function(pattern,replacement,x,all = TRUE,...){ FUN &lt;- if (all) gsub else sub for (i in seq_len(min(length(pattern),length(replacement)))){ x &lt;- FUN(pattern = pattern[i],replacement = replacement[i],x,...) } x } vsub(my_pattern,my_replacement,start_string) </code></pre> <p>But of course, one of the reasons that there isn't a built-in function for this that's well known is probably that sequential replacements like this can't be pretty fragile, because they are so order dependent:</p> <pre><code>vsub(rev(my_pattern),rev(my_replacement),start_string) [1] "i" "[this w[this was an a]s [this was an a] c]" [3] "[this was an a]" "g" [5] "j" "d" [7] "f" "[this w[this was an a]s [this was an a] b]" [9] "h" "e" </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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