rename column with a vector in r code example
Example 1: r rename column based on variable
df %>% rename(!!variable := name_of_col_from_df)
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.