title: Using dplyr to apply a function of several columns of an R data frame
body: <p><em>Using dplyr’s “verbs,” how can I apply a (general) function to a column of an R data frame, if that function depends on multiple columns of the data frame?</em></p>
  
  <p>Here’s a concrete example of the type of situation that I face. I have a data frame like this:</p>
  
  <pre><code>df &lt;- data.frame(
      d1 = c('2016-01-30 08:40:00 UTC', '2016-03-06 09:30:00 UTC'),
      d2 = c('2016-01-30 16:20:00 UTC', '2016-03-06 13:20:00 UTC'),
      tz = c('America/Los_Angeles', 'America/Chicago'), stringsAsFactors = FALSE)
  </code></pre>
  
  <p>I want to convert the UTC times to local times, to get a data frame like this:</p>
  
  <pre><code>                   d1                  d2                  tz
  1 2016-01-30 00:40:00 2016-01-30 08:20:00 America/Los_Angeles
  2 2016-03-06 03:30:00 2016-03-06 07:20:00     America/Chicago
  </code></pre>
  
  <p>To do this, I would like to apply the following function, which converts UTC time to local time using the lubridate library, to the date columns:</p>
  
  <pre><code>getLocTime &lt;- function(d, tz) {
      as.character(with_tz(ymd_hms(d), tz))
  }
  </code></pre>
  
  <p>Using dplyr, it seems that the transformation</p>
  
  <pre><code>df %&gt;% mutate(d1 = getLocTime(d1, tz), d2 = getLocTime(d2, tz))
  </code></pre>
  
  <p>should do the trick. However, it fails with the complaint <code>Error in eval(expr, envir, enclos): invalid 'tz' value</code>.</p>
  
  <p>The only way I've managed to do the conversion to local time is with the rather ungainly assignment</p>
  
  <pre><code>df[c('d1', 'd2')] &lt;- lapply(c('d1', 'd2'),
                              function(x) unlist(Map(getLocTime, df[[x]], df$tz)))
  </code></pre>
  
  <p><em>Is there in fact a natural way to perform this transformation using dplyr idioms?</em></p>