How to rename a column to a variable name "in a tidyverse way"

lebelinoz picture lebelinoz · Aug 3, 2017 · Viewed 7.2k times · Source

I've created a simple data frame (dput below):

    date      ticker     value
------------------------------
  2016-06-30  A2M.ASX   0.0686
  2016-07-29  A2M.ASX  -0.0134
  2016-08-31  A2M.ASX  -0.0650
  2016-09-30  A2M.ASX   0.0145
  2016-10-31  A2M.ASX   0.3600
  2016-11-30  A2M.ASX  -0.1429

I want to change the value column's name to whatever is in my metric variable name, and I want to do it in a dplyr way.

My sample data:

df = structure(list(date = c("2016-06-30", "2016-07-29", "2016-08-31", "2016-09-30", "2016-10-31", "2016-11-30"), ticker = c("A2M.ASX", "A2M.ASX", "A2M.ASX", "A2M.ASX", "A2M.ASX", "A2M.ASX"), value = c(0.0686, -0.0134, -0.065, 0.0145, 0.36, -0.1429)), .Names = c("date", "ticker", "value"), row.names = c(NA, 6L), class = "data.frame")
metric = "next_return"

I know how to do it in one line:

colnames(df)[3] = metric

But I want do it in a tidyverse way so I can use it in a pipe. I've been tinkering with replace_ but I only manage to get errors:

> dplyr::rename_(df, "ticker" = metric)
Error: `next_ret_1M` contains unknown variables

Answer

MrFlick picture MrFlick · Aug 3, 2017

With the newest dplyr (>0.7.0) you would use

rename(df, !!metric:=value)

The syntax is "new_name=old_name" and you need to use := with !! to put a variable on the left side of a parameter name.