rename a column in r dataframe code example

Example 1: r change column name in dataframe

df <- df %>%
  rename(newName1 = oldName1 ,
         newName2 = oldName2)

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:

C Example