title: R how to replace substrings within a longer string with a new substring
body: <p>I have a long vector. Each element is a string.
  Each string can be split into substrings separated by ', '.</p>
  
  <p>I want to check if each string in my vector contains at least one 'bad' string. If it does, then the whole SUBstring that contains that 'bad' string should be replaced with a new string. I've written a long function with loops. But I could swear there must be an easier way of doing it - maybe with stringr? 
  Thank you so much for your advice!</p>
  
  <pre><code># Create an example data frame:
  test &lt;- data.frame(a = c("str1_element_1_aaa, str1_element_2",
                           "str2_element_1",
                           "str3_element_1, str3_element_2_aaa, str3_element_3"),
                     stringsAsFactors = F)
  test
  str(test)
  
  # Defining my long function that checks if each string in a
  # vector contains a substring with a "bad" string in it.
  # If it does, that whole substring is replaced with a new string:
  library(stringr)
  mystring_replace = function(strings_vector, badstring, newstring){
    with_string &lt;- grepl(badstring, strings_vector)  # what elements contain badstring?
    mysplits &lt;- str_split(string = test$a[with_string], pattern = ', ') # split those elements with badstring based on ', '
    for (i in 1:length(mysplits)) {   # loop through the list of splits:
      allstrings &lt;- mysplits[[i]]
      for (ii in 1:length(allstrings)) {  # loop through substrings
        if (grepl(badstring, allstrings[ii])) mysplits[[i]][ii] &lt;- newstring
      }
    }
    for (i in seq_along(mysplits)) {  # merge the split elements back together
      mysplits[[i]] &lt;- paste(mysplits[[i]], collapse = ", ")
    }
    strings_vector[with_string] &lt;- unlist(mysplits)
    return(strings_vector)
  }
  # Test
  mystring_replace(test$a, badstring = '_aaa', newstring = "NEW")
  </code></pre>