Home ยป Changing all data frame column names to upper case in R

Changing all data frame column names to upper case in R

  • by
changing all column names to uppercase in R
Want to do a random act of kindness? Share this post.

One of the compulsive things I do in my programming life is trying to keep all column names in uppercase. Inbetween my code you can often find a line of code that manually adjusts the column names of a data frame. However, I read the following in a colleague’s code today, and I thought I’d share it.

The following function loops over all the objects in an environment. Then it checks if it is a data frame (or data.table). If so, it changes the column names of the data frames to uppercase.

up <- function() {
  for (df in ls(.GlobalEnv)[1:(length(ls(.GlobalEnv))-1)]){
    e <<- .GlobalEnv
    if (is.data.frame(e[[df]])) {
      colnames(e[[df]]) <<- toupper(colnames(e[[df]]))
    }
  }
  rm(e,pos=".GlobalEnv")
}

Now you can simply run the following four characters of code after every chunk of code to guarantee all your data frame column names are properly cased.

up()

Good luck!

Want to do a random act of kindness? Share this post.