title: How to compare one column to a series of related dummy variables without a for loop in R
body: <p>I have working R code, but it is inelegant and inefficient. I am wondering if there is a better way: i.e. how can I vectorize this process and/or reduce the computing time?</p>
  
  <pre><code>library(data.table)
  dt &lt;- data.table(
      visited_a = c(1, 1, 0, 0),
      visited_b = c(1, 0, 0, 0),
      visited_c = c(0, 0, 1, 1),
      purchased = c("b", "b", "c", "a")
  )
  </code></pre>
  
  <p>My data.table has dummy indicators for whether a consumer visited a store in 2017. So <code>visited_a = 0</code> means she did not visit store <code>a</code> in 2017 while <code>visited_b = 1</code> means she did visit store <code>b</code> in 2017. The data also list which store the consumer purchased from in 2018; all of these consumers made a purchase. Thus a consumer may or may not have visited the store (last year) that she purchased from (this year). </p>
  
  <p>I want to add a variable <code>purchased_was_visited</code> to capture this. The solution would be:</p>
  
  <pre><code>dt$purchased_was_visited &lt;- c(1, 0, 1, 0)
  </code></pre>
  
  <p>Here is my extraordinary inelegant code that sadly loops through the data.table one row at a time.  There must be a better way!</p>
  
  <pre><code>dt[ , purchased_was_visited := NA]
  for(i in 1:nrow(dt)) {
      brand &lt;- dt[i, purchased]
      col &lt;- paste0("visited_", brand)
      was_it &lt;- dt[i, ..col]
      dt[i, purchased_was_visited := was_it]
  }
  </code></pre>