I\'m working with an imported data set that corresponds to the extract below:
set.seed(1)
dta <- data.frame(\"This is Column One\" = runif(n = 10),
You can also try this
set.seed(1)
dta <- data.frame("This is Column One" = runif(n = 10),
"Another amazing Column name" = runif(n = 10),
"!## This Columns is so special€€€" = runif(n = 10),
check.names = FALSE)
dta <- dta %>%
setNames(gsub("[^[:alnum:] ]", perl = TRUE,
"",
names(.))) %>%
setNames(gsub("(\\w)(\\w*)",
"\\U\\1\\L\\2",
perl = TRUE,
names(.)))
names(dta)
[1] "This Is Column One" "Another Amazing Column Name" " This Columns Is So Special"
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.
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.
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
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
Using Stringr and Dplyr, and the dot operator:
dta %>%
dplyr::rename_all(funs(
stringr::str_replace_all( ., "[[:punct:]]", "_" )
))
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