title: R dplyr: rename variables using string functions
body: <p>(Somewhat related question: <a href="https://stackoverflow.com/questions/26470465/enter-new-column-names-as-string-in-dplyrs-rename-function">Enter new column names as string in dplyr&#39;s rename function</a>)</p>
  
  <p>In the middle of a <code>dplyr</code> chain (<code>%&gt;%</code>), I would like to replace multiple column names with functions of their old names (using <code>tolower</code> or <code>gsub</code>, etc.)</p>
  
  <pre><code>library(tidyr); library(dplyr)
  data(iris)
  # This is what I want to do, but I'd like to use dplyr syntax
  names(iris) &lt;- tolower( gsub("\\.", "_", names(iris) ) )
  glimpse(iris, 60)
  # Observations: 150
  # Variables:
  #   $ sepal_length (dbl) 5.1, 4.9, 4.7, 4.6, 5.0, 5.4, 4.6,...
  #   $ sepal_width  (dbl) 3.5, 3.0, 3.2, 3.1, 3.6, 3.9, 3.4,...
  #   $ petal_length (dbl) 1.4, 1.4, 1.3, 1.5, 1.4, 1.7, 1.4,...
  #   $ petal_width  (dbl) 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.3,...
  #   $ species      (fctr) setosa, setosa, setosa, setosa, s...
  
  # the rest of the chain:
  iris %&gt;% gather(measurement, value, -species) %&gt;%
    group_by(species,measurement) %&gt;%
    summarise(avg_value = mean(value)) 
  </code></pre>
  
  <p><strike>I see <code>?rename</code> takes the argument <code>replace</code> as a <code>named character vector, with new names as values, and old names as names.</code></strike></p>
  
  <p>So I tried:</p>
  
  <pre><code>iris %&gt;% rename(replace=c(names(iris)=tolower( gsub("\\.", "_", names(iris) ) )  ))
  </code></pre>
  
  <p>but this (a) returns <code>Error: unexpected '=' in iris %&gt;% ...</code> and (b) requires referencing by name the data frame from the previous operation in the chain, which in my real use case I couldn't do.</p>
  
  <pre><code>iris %&gt;% 
    rename(replace=c(    )) %&gt;% # ideally the fix would go here
    gather(measurement, value, -species) %&gt;%
    group_by(species,measurement) %&gt;%
    summarise(avg_value = mean(value)) # I realize I could mutate down here 
                                       #  instead, once the column names turn into values, 
                                       #  but that's not the point
  # ---- Desired output looks like: -------
  # Source: local data frame [12 x 3]
  # Groups: species
  # 
  #       species  measurement avg_value
  # 1      setosa sepal_length     5.006
  # 2      setosa  sepal_width     3.428
  # 3      setosa petal_length     1.462
  # 4      setosa  petal_width     0.246
  # 5  versicolor sepal_length     5.936
  # 6  versicolor  sepal_width     2.770
  # ... etc ....  
  </code></pre>