Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Changing a column's name to titlecase using dplyr, by means of a function

Consider the very simple example of renaming the lat column of quakes to Lat, the titlecase version.

library(dplyr)

quakes %>%
  rename(Lat = lat)

I would like to write this as a function. My attempt so far has been

titlecase_col <- function(df, col_name) {
  quakes %>%
    rename(tools::toTitleCase(as_string(ensym(col_name))) := {{col_name}})
}

> titlecase_col(quakes, lat)

Error: The LHS of `:=` must be a string or a symbol

The error doesn’t make sense to me, since in my mind, that is a string, so I must be doing something wrong here.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If we add the !! to evaluate and correct the syntax errors (input argument was df, whereas inside the function quakes was used – it could be a potential bug), it would work

titlecase_col <- function(df, col_name) {
  df %>%
    rename(!!tools::toTitleCase(rlang::as_string(ensym(col_name))) 
                  := {{col_name}})
}

-testing

> titlecase_col(quakes, lat) %>%
     head
     Lat   long depth mag stations
1 -20.42 181.62   562 4.8       41
2 -20.62 181.03   650 4.2       15
3 -26.00 184.10    42 5.4       43
4 -17.97 181.66   626 4.1       19
5 -20.42 181.96   649 4.0       11
6 -19.68 184.31   195 4.0       12
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading