Applying dplyr's rename to all columns while using pipe operator
I know this is an old question, and I'm sure you found the solution by now, but I stumbled here searching for the same question, and ultimately found a few new ways to do this.
Dplyr
Using dplyr 0.6.0
and above, there is now a rename_all
function:
dta %>%
rename_all(funs(gsub("[[:punct:]]", "", make.names(names(dta)))))
Which works, but it's a little messy to me. If you want more flexibility with dplyr
, you can also call on:
rename_at
rename_if
Janitor
This is a pretty nice package (with plenty of additional utility) that can easily clean up column names:
library(janitor)
dta %>%
clean_names()
Which will rename and clean all column names to the following:
[1] "this_is_column_one" "another_amazing_column_name" "x_this_columns_is_so_special"
Everything becomes snake_case rather than CamelCase, but overall clean_names
is very flexible in the column names it handles. If that IS a deal breaker, you can use yet another package snakecase
for its function to_big_camel_case()
within the rename_all
function...although that is starting to get a little too esoteric
Set column names with the pipe like so:
iris %>% `colnames<-`(c("newcol1", "newcol2", "newcol3", "newcol4", "newcol5"))
Which returns
newcol1 newcol2 newcol3 newcol4 newcol5
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
mtcars %>%
data.table::setnames(
old = mtcars %>% names(),
new = mtcars %>% names() %>% paste0("_new_name")
)
The function setnames
in data.table
package is to rename the column names in data frame. old
and new
are two arguments in this function we need.
mtcars %>% names()
outputs the column names of data frame mtcars
in pipeline %>%
way, so you can also use names(mtcars)
. They are same thing.
In this minimal example, I rename the column names in pipeline %>%
and add all old column names with a postfix using paste0
function. You can add prefix, postfix or other rules.