73

After importing a file, I always try try to remove spaces from the column names to make referral to column names easier.

Is there a better way to do this other then using transform and then removing the extra column this command creates?

This is what I use now:

names(ctm2)
#tranform function does this, but requires some action
ctm2<-transform(ctm2,dymmyvar=1)
#remove dummy column
ctm2$dymmyvar <- NULL
names(ctm2)
4
  • 3
    Use the inject.dots function: inject.dots <- function(df) {names(df) <- sub(" ", ".", names(df));df} May 21, 2012 at 15:48
  • 2
    On a serious side I'm surprised R imports in column names with spaces and doesn't fix it automatically. May 21, 2012 at 15:49
  • 8
    @TylerRinker The read.table function does that by default with the make.names function.
    – IRTFM
    May 21, 2012 at 16:00
  • 3
    @TylerRinker: yes it does. Both read.csv/read.table(..., check.names=T). And the default is TRUE.
    – smci
    Jun 26, 2018 at 22:47

13 Answers 13

85

There exists more elegant and general solution for that purpose:

tidy.name.vector <- make.names(name.vector, unique=TRUE)

make.names() makes syntactically valid names out of character vectors. A syntactically valid name consists of letters, numbers and the dot or underline characters and starts with a letter or the dot not followed by a number.

Additionally, flag unique=TRUE allows you to avoid possible dublicates in new column names.

As code to implement

d<-read_delim(urltxt,delim='\t',)
names(d)<-make.names(names(d),unique = TRUE)
4
  • 8
    grate solution. Here a tidy alternative: df %>% dplyr::rename_all(funs(make.names(.)))
    – avallecam
    May 30, 2018 at 20:25
  • 6
    funs() is soft-deprecated as of dplyr 0.8.0 so a tidy alternative would now be: df %>% dplyr::rename_all(list(~make.names(.)))
    – GISHuman
    May 14, 2019 at 17:55
  • 5
    df %>% rename_all(make.names)
    – nniloc
    Jan 26, 2021 at 20:29
  • 3
    rename_all() is superseded in dplyr 1.0.7. so it would be better to use df %>% rename_with(make.names) Aug 29, 2021 at 16:00
49

There is a very useful package for that, called janitor that makes cleaning up column names very simple. It removes all unique characters and replaces spaces with _.

library(janitor)

#can be done by simply
ctm2 <- clean_names(ctm2)

#or piping through `dplyr`
ctm2 <- ctm2 %>%
        clean_names()
39

To replace only the first space in each column you could also do:

names(ctm2) <- sub(" ", ".", names(ctm2))

or to replace all spaces (which seems like it would be a little more useful):

names(ctm2) <- gsub(" ", "_", names(ctm2))

or, as mentioned in the first answer (though not in a way that would fix all spaces):

spaceless <- function(x) {colnames(x) <- gsub(" ", "_", colnames(x));x}
newDF <- spaceless(ctm2)

where x is the name of your data.frame. I prefer to use "_" to avoid issues with "." as part of an ID.

The point is that gsub doesn't stop at the first instance of a pattern match.

1
  • The problem with this, at least on my end, is: If a column name has more than one space, it will only replace the first Mar 11, 2016 at 16:15
14

dplyr::select_all() can be used to reformat column names. This example replaces spaces and periods with an underscore and converts everything to lower case:

iris %>%  
  select_all(~gsub("\\s+|\\.", "_", .)) %>% 
  select_all(tolower) %>% 
  head(2)
  sepal_length sepal_width petal_length petal_width species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
12

Assign the names like this. This works best. It replaces all white spaces in the name with underscore.

names(ctm2)<-gsub("\\s","_",names(ctm2))

1
  • 1
    The most direct, most concise solution, by far. May 18, 2018 at 17:29
11

best solution I found so far is

names(ctm2) %<>% stringr::str_replace_all("\\s","_") %>% tolower

credit goes to commenters and other answers

1
  • Is there a way to integrate this into an apply-type function in order to rename columns in multiple datasets?
    – Addison
    Dec 2, 2020 at 16:36
9

It's often convenient to change the names of your columns within one chunk of dplyr code rather than renaming the columns after you've created the data frame. Piping in rename_all() is very useful in these situations:

ctm2 %>% rename_all(function(x) gsub(" ", "_", x))

The code above will replace all spaces in every column name with an underscore.

8

UDPDATE 2022 Aug:

df %>% rename_with(make.names)

OLD code was: (still works though) as of Jan 2021: drplyr solution that is brief and uses no extra libraries is

df %<>% dplyr::rename_all(make.names)

credit goes to commenter.

1
6

Alternatively, you may be able to achieve the same results with the stringr package.

names(ctm2) <- names(ctm2) %>% stringr::str_replace_all("\\s","_")

3

There is an easy way to remove spaces in column names in data.table. You will have to convert your data frame to data table.

setnames(x=DT, old=names(DT), new=gsub(" ","",names(DT)))

Country Code will be converted to CountryCode

1
  • 1
    Omit old and it will have the same result. (This is covered in the docs.)
    – Frank
    Aug 15, 2017 at 19:43
3

You can also use combination of make names and gsub functions in R.

names(ctm2)<- gsub("\\.","_", make.names(names(ctm2), unique = T))

Above code will do 2 things at a time:

  1. It will create unique names for all columns - for e.g. same names will be converted to unique e.g. c("ab","ab") will be converted to c("ab","ab2")
  2. It will replace dots with Underscores. it becomes easy (just double click on name) when you try to select column name which has underscore as compared to column names with dots. selecting column names with dots is very difficult.
2

Just assign to names(ctm2):

  names(ctm2) <- c("itsy", "bitsy", "eeny", "meeny")

or in data-driven way:

  names(ctm2) <- paste("myColumn", 1:ncol(ctm2), sep="")

Another possibility is to edit your source file...

0

If you use read.csv() to import your data (which replaces all spaces " " with ".") you can replace these instead with an underscore "_" using:

names(df) <- gsub("\\.", "_", names(df))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.