Quickly Renaming Variables in R

Real programmers don’t comment their code. It was hard to write, it should be hard to understand.

One of the nice things in R is that you can write your own functions to make sucky tasks suck less, and there is little that sucks so much as tidying the data. The first step (for me) is usually dealing with the variable names.

To save a lot of typing, the following code (executed with quick.rename(workData) if workData is the data.table or tibble with the variables to rename) clears the console and prints out the code to rename the variables (mind the trailing curly bracket).

quick.rename <- function(dataTable) {
cat(paste0("\014",deparse(substitute(dataTable)), " <- ", deparse(substitute(dataTable)), " %>%\n\trename( `NEWNAME` = ", paste0(sprintf("`%s`", names(dataTable)), collapse = ",\n\t\t`NEWNAME` = ")), ")", sep="")

There were earlier versions of this code which were more easy to understand, but I kinda like this iteration. And yeah, it’s a chimera of different code styles and not how you would do it. But I’m a sorcerer, not a wizard, so there you go. 😉