-1

I'm trying to rename a variable in a dataframe but can't get the unquoting part to work. I have read http://dplyr.tidyverse.org/articles/programming.html and looking at different examples but unfortunately just can't figure it out somehow. This is what I'm currently using, I want to rename the column "x" to "x2" (both are variables):

df = data.frame(x = c(1,2,3), y = c(2,3,4))
variable_to_rename = "x"
new_variable_name = "x2"
df %>%
  rename_vars(names(.), !! variable_to_rename = !! new_variable_name)

The desired output is the dataframe:

data.frame(x2 = c(1,2,3), y = c(2,3,4))

As I just commented: I found the following working code:

df %>%
  rename(!!new_variable_name := !!rlang::sym(variable_to_rename))
onnhoJ
  • 56
  • 7
  • Sorry, found the answer already: df %>% rename(!!new_variable_name := !!rlang::sym(variable_to_rename)) – onnhoJ Aug 17 '17 at 08:01
  • 1
    see also this answer https://stackoverflow.com/a/44452676/3926543 and the first comment. Hope it helps. – mt1022 Aug 17 '17 at 08:06

2 Answers2

0

You can maybe just use names ? names(df)[1] <- "x2"

Orhan Yazar
  • 909
  • 7
  • 19
0

The easiest approach to rename a single column is as suggested here. But if you want to use the dplyr::rename(), then look at the below answer.


Usage of rename() function as below would do the needful.

df <- rename(df, x2 = x)
df
#  x2 y
#1  1 2
#2  2 3
#3  3 4
Prradep
  • 5,506
  • 5
  • 43
  • 84