31

Is it possible to set all column names to upper or lower within a dplyr or magrittr chain?

In the example below I load the data and then, using a magrittr pipe, chain it through to my dplyr mutations. In the 4th line I use the tolower function , but this is for a different purpose: to create a new variable with lowercase observations.

mydata <- read.csv('myfile.csv') %>%
    mutate(Year = mdy_hms(DATE),
           Reference = (REFNUM),
           Event = tolower(EVENT)

I'm obviously looking for something like colnames = tolower but know this doesn't work/exist.

I note the dplyr rename function but this isn't really helpful.

In magrittr the colname options are:

set_colnames instead of base R's colnames<-
set_names instead of base R's names<-

I've tried numerous permutations with these but no dice.

Obviously this is very simple in base r.

names(mydata) <- tolower(names(mydata))

However it seems incongruous with the / philosophies that you'd have to do that as a clunky one liner, before moving on to an elegant chain of dplyr/magrittr code.

faidherbard
  • 983
  • 8
  • 19
RDJ
  • 4,052
  • 9
  • 36
  • 54
  • 1
    See [@Moody_Mudskipper's](https://stackoverflow.com/users/2270475/moody-mudskipper) answer to learn more about `dplyr::rename_all()`. – Cristian E. Nuno Aug 21 '18 at 17:50

5 Answers5

71

with {dplyr} we can do :

mydata %>% rename_with(tolower)

rename_all() can be used for the same effect but has been superseded.

moodymudskipper
  • 46,417
  • 11
  • 121
  • 167
25
iris %>% setNames(tolower(names(.))) %>% head

Or equivalently use replacement function in non-replacement form:

iris %>% `names<-`(tolower(names(.))) %>% head
iris %>% `colnames<-`(tolower(names(.))) %>% head  # if you really want to use `colnames<-`
BrodieG
  • 51,669
  • 9
  • 93
  • 146
22

Using magrittr's "compound assignment pipe-operator" %<>% might be, if I understand your question correctly, an even more succinct option.

library("magrittr")
names(iris) %<>% tolower

?`%<>%` # for more
Kevin
  • 381
  • 1
  • 5
2
mtcars %>% 
set_colnames(value = casefold(colnames(.), upper = FALSE)) %>% 
head

casefold is available in base R and can convert in both direction, i.e. can convert to either all upper case or all lower case by using the flag upper, as need might be.

Also colnames() will use only column headers for case conversion.

Frash
  • 724
  • 1
  • 10
  • 19
2

You could also define a function:

upcase <- function(df) {
  names(df) <- toupper(names(df))
  df
}

library(dplyr)

mtcars %>% upcase %>% select(MPG)
Carl
  • 5,569
  • 6
  • 39
  • 74
  • IMHO it's best solution. I named this function `names_to_upper` (and second as `names_to_lower`), `colnames_` would look good too: `mtcars %>% colnames_to_upper %>% select(MPG)`. – Marek Nov 23 '16 at 08:41