title: Using grep on multiple columns to create new variable in R
body: <p>I'm trying to run grep across multiple columns to create a new binary variable in my dataset. I can't share my real dataset, but I've created a sample one to demonstrate my issue:</p>
  <pre><code>breakfast &lt;- c(&quot;apple orange&quot;, &quot;orange banana&quot;, &quot;apple&quot;)
  lunch &lt;- c(&quot;orange&quot;, &quot;apple orange&quot;, &quot;apple banana&quot;)
  df &lt;- data.frame(breakfast, lunch)
  </code></pre>
  <p>In this example, my goal is to create a new binary variable in this dataframe called &quot;apple&quot; that is 1 if either the &quot;breakfast&quot; or &quot;lunch&quot; columns contain &quot;apple&quot; and 0 if they do not.</p>
  <p>I can achieve this by using nested ifelse statements and grepl:</p>
  <pre><code>df$apple &lt;- ifelse(grepl(&quot;apple&quot;, df$breakfast), 1,
              ifelse(grepl(&quot;apple&quot;, df$lunch), 1, 0))
  </code></pre>
  <p>In my real dataset though, I need to scan more than just two columns and repeat the process for multiple strings, so I'm hoping to create a function that will run it through the columns for me. What's the best way to do this?</p>
  <p>I've found several posts that address similar questions, but many of them are based on variables with single values to match to rather than concatenated strings (== &quot;apple&quot; rather than contains &quot;apple&quot;). I'm also struggling with how to adapt existing examples to then create the binary variable I'm looking for.</p>