dplyr replace pass column name as variable code example

Example 1: r rename column based on variable

rename(df, !!metric:=value)

Example 2: 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:

Misc Example