Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dplyr or Magrittr - tolower?

Tags:

r

dplyr

magrittr

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 dplyr/magrittr philosophies that you'd have to do that as a clunky one liner, before moving on to an elegant chain of dplyr/magrittr code.

like image 926
RDJ Avatar asked Mar 25 '15 18:03

RDJ


2 Answers

dplyr now allows this:

mydata %>% rename_all(tolower)
like image 188
Moody_Mudskipper Avatar answered Oct 22 '22 06:10

Moody_Mudskipper


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<-`
like image 25
BrodieG Avatar answered Oct 22 '22 07:10

BrodieG