1# Rename column by name: change "beta" to "two"
2names(d)[names(d)=="beta"] <- "two"
3d
4#> alpha two gamma
5#> 1 1 4 7
6#> 2 2 5 8
7#> 3 3 6 9
8
9# You can also rename by position, but this is a bit dangerous if your data
10# can change in the future. If there is a change in the number or positions of
11# columns, then this can result in wrong data.
12
13# Rename by index in names vector: change third item, "gamma", to "three"
14names(d)[3] <- "three"
15d
16#> alpha two three
17#> 1 1 4 7
18#> 2 2 5 8
19#> 3 3 6 9
201names(d) <- sub("^alpha$", "one", names(d))
2d
3#> one two three
4#> 1 1 4 7
5#> 2 2 5 8
6#> 3 3 6 9
7
8# Across all columns, replace all instances of "t" with "X"
9names(d) <- gsub("t", "X", names(d))
10d
11#> one Xwo Xhree
12#> 1 1 4 7
13#> 2 2 5 8
14#> 3 3 6 9
15
16# gsub() replaces all instances of the pattern in each column name.
17# sub() replaces only the first instance in each column name.
18