How to rename a column in a variable name "in reverse order"

I created a simple data frame ( dputbelow):

    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 column name valueto everything that is in the variable name metric, and I want to do this with dplyr.

My details:

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 this on one line:

colnames(df)[3] = metric

But I want to do this with help tidyverseso that I can use it in a pipe. I do replace_, but I manage to get errors:

> dplyr::rename_(df, "ticker" = metric)
Error: `next_ret_1M` contains unknown variables
+4
source share
1 answer

With the latest dplyr (> 0.7.0) you should use

rename(df, !!metric:=value)

The syntax is "new_name = old_name", and you need to use :=c !!to place the variable on the left side of the parameter name.

+8

Source: https://habr.com/ru/post/1682896/


All Articles