```{r setup, include=FALSE}
library(tint)
knitr::opts_chunk$set(tidy = FALSE)
options(htmltools.dir.version = FALSE)

library("seplyr")
sc <- sparklyr::spark_connect(version='2.2.0', 
   master = "local")
d <- dplyr::starwars %.>%
  select_se(., qc(name, height, mass, hair_color, 
                 skin_color, eye_color, birth_year, 
                 gender, homeworld, species)) %.>%
  dplyr::copy_to(sc, ., "starwars")
```

This is my (new)^["New" also meaning we need the latest versions 
of [`wrapr`](https://winvector.github.io/wrapr/) and [`seplyr`](https://winvector.github.io/seplyr/).] favorite way to bulk rename columns in [`R`](https://www.r-project.org),
especially when using [`sparklyr`](https://spark.rstudio.com) to work with big data. 

There are, of course, many other ways to do this.

Consider the following data:^[Source code for this note can be found [here](https://github.com/WinVector/WinVector.github.io/blob/master/FluidData/Renaming.Rmd).]

```{r show1}
class(d)

d %.>%
  head(.) %.>%
  knitr::kable(.)
```

Notice this data is a remote `Spark` data handle (not an in-memory `data.frame`).

Suppose (for no reason at all) we want all columns with under-bars to be in upper case.

This is easy to achieve:^[People have asked, so I will discuss it (again).
A lot of the other methods for renaming columns
do not work with `Spark` data. For example, using the current CRAN versions of 
`rlang` (`r packageVersion("rlang")`),
`dplyr` (`r packageVersion("dplyr")`),
`dbplyr` (`r packageVersion("dbplyr")`),
`sparklyr`  (`r packageVersion("sparklyr")`): both `rlang::set_names(d, toupper)`,
and `dplyr::rename(d, HAIR_COLOR=hair_color, SKIN_COLOR=skin_color)` throw
when given `Spark` data handles.  This is a topic of some discussion: 
[1](https://github.com/rstudio/sparklyr/issues/678),
[2](https://github.com/rstudio/sparklyr/issues/900),
[3](https://github.com/tidyverse/dplyr/issues/2776),
[4](https://github.com/tidyverse/dplyr/issues/2860),
and [5](https://stackoverflow.com/questions/45622262/sparklyr-change-all-column-names-spark-dataframe).]


```{r rename1}
library("seplyr")
# requires version at least 1.0.1
packageVersion("wrapr") 
# requires version at least 0.1.6
packageVersion("seplyr") 

# find columns matching our condition
colsToRename <- grepdf(".*_.*", d)
print(colsToRename)

# build the right to left (NEW := old) assignment
mapping <- toupper(colsToRename) := colsToRename
print(mapping)

# apply the transform
d %.>% 
  rename_se(., mapping) %.>%
  head(.) %.>%
  knitr::kable(.)
```

 
```{r cleanup, include=FALSE}
sparklyr::spark_disconnect(sc)
```

