rename values of a variable in r code example

Example 1: rename columns based on a variable in r

df <- rename(df, new_name = old_name) #For renaming dataframe column
 
tbl <- rename(tbl, new_name = old_name) #For renaming tibble column
 
tbl <- tbl %>% rename(new_name = old_name) #For renaming tibble column using dplyrpipe 
                                           #operator

Example 2: r rename column based on variable

rename(df, !!metric:=value)

Example 3: r rename column based on variable

names(d) <- sub("^alpha$", "one", names(d))
d
#>   one two three
#> 1   1   4     7
#> 2   2   5     8
#> 3   3   6     9

# Across all columns, replace all instances of "t" with "X"
names(d) <- gsub("t", "X", names(d))
d
#>   one Xwo Xhree
#> 1   1   4     7
#> 2   2   5     8
#> 3   3   6     9

# gsub() replaces all instances of the pattern in each column name.
# sub() replaces only the first instance in each column name.

Tags:

R Example