title: Loops: How can I loop case_when function in R?
body: <p>Here's the code, where I am trying to create a variable by detecting the words and matching them. Here I use <code>dplyr</code> package and its function <code>mutate</code> in combination with <code>case_when</code>. The problem is I am adding each one of the values manually as you see. How can I <strong>automate</strong> it by applying some loop functions to match the two?</p>
  <pre><code>city &lt;- LETTERS #26 cities
  district &lt;- letters[10:20] #11 districts
  streets &lt;- paste0(district, district)
  streets &lt;- streets[-c(5:26)] #4 streets
  
  df &lt;- data.frame(x = c(1:5), 
             address = c(&quot;A, b, cc,&quot;, &quot;B, dd&quot;, &quot;a, dd&quot;, &quot;C&quot;, &quot;D, a, cc&quot;))
  
  library(dplyr)
  library(stringi)
  
  df2 &lt;- df %&gt;%
    mutate(districts = case_when(
      stri_detect_fixed(address, &quot;b&quot;) ~ &quot;b&quot;,   #address[1]
                                               #address[2]
      stri_detect_fixed(address, &quot;a&quot;) ~ &quot;a&quot;,   #address[3]
                                               #address[4]
      stri_detect_fixed(address, &quot;cc&quot;) ~ &quot;cc&quot;  #address[5]
  ))
  </code></pre>
  <p>The code scans through <code>address</code> for the value in <code>district</code> vector. I would love to do the same for <code>city</code> and <code>street</code> variables. So I used the modified version of the <a href="https://stackoverflow.com/questions/52708078/using-a-loop-to-define-values-of-case-when-in-r">code from another question</a> in Stack Overflow. It produces an error.</p>
  <pre><code>for (j in town_village2) {
  trn_house3[,93] &lt;- case_when(
        stri_detect_fixed(trn_house3[1:6469, 4], j) ~ j)
  }
  </code></pre>
  <p>I seek to produce this result:</p>
  <pre><code>x    address      city     district   street
  1    A, b, cc,      A        b          cc  
  2    B, dd          B        NA         dd
  3    a, dd          NA       a          dd
  4    C              C        NA         NA
  5    D, a, cc       D        a          cc
  
  </code></pre>