Home > Software engineering >  Changing a column's name to titlecase using dplyr, by means of a function
Changing a column's name to titlecase using dplyr, by means of a function

Time:12-02

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.

CodePudding user response:

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
  • Related