About Me Blog
A tutorial on tidy cross-validation with R Analyzing NetHack data, part 1: What kills the players Analyzing NetHack data, part 2: What players kill the most Building a shiny app to explore historical newspapers: a step-by-step guide Classification of historical newspapers content: a tutorial combining R, bash and Vowpal Wabbit, part 1 Classification of historical newspapers content: a tutorial combining R, bash and Vowpal Wabbit, part 2 Curly-Curly, the successor of Bang-Bang Dealing with heteroskedasticity; regression with robust standard errors using R Easy time-series prediction with R: a tutorial with air traffic data from Lux Airport Exporting editable plots from R to Powerpoint: making ggplot2 purrr with officer Fast food, causality and R packages, part 1 Fast food, causality and R packages, part 2 For posterity: install {xml2} on GNU/Linux distros Forecasting my weight with R From webscraping data to releasing it as an R package to share with the world: a full tutorial with data from NetHack Get text from pdfs or images using OCR: a tutorial with {tesseract} and {magick} Getting data from pdfs using the pdftools package Getting the data from the Luxembourguish elections out of Excel Going from a human readable Excel file to a machine-readable csv with {tidyxl} Historical newspaper scraping with {tesseract} and R How Luxembourguish residents spend their time: a small {flexdashboard} demo using the Time use survey data Imputing missing values in parallel using {furrr} Intermittent demand, Croston and Die Hard Looking into 19th century ads from a Luxembourguish newspaper with R Making sense of the METS and ALTO XML standards Manipulate dates easily with {lubridate} Manipulating strings with the {stringr} package Maps with pie charts on top of each administrative division: an example with Luxembourg's elections data Missing data imputation and instrumental variables regression: the tidy approach Modern R with the tidyverse is available on Leanpub Objects types and some useful R functions for beginners Pivoting data frames just got easier thanks to `pivot_wide()` and `pivot_long()` R or Python? Why not both? Using Anaconda Python within R with {reticulate} Searching for the optimal hyper-parameters of an ARIMA model in parallel: the tidy gridsearch approach Some fun with {gganimate} Statistical matching, or when one single data source is not enough The best way to visit Luxembourguish castles is doing data science + combinatorial optimization The never-ending editor war (?) The year of the GNU+Linux desktop is upon us: using user ratings of Steam Play compatibility to play around with regex and the tidyverse Using Data Science to read 10 years of Luxembourguish newspapers from the 19th century Using a genetic algorithm for the hyperparameter optimization of a SARIMA model Using cosine similarity to find matching documents: a tutorial using Seneca's letters to his friend Lucilius Using linear models with binary dependent variables, a simulation study Using the tidyverse for more than data manipulation: estimating pi with Monte Carlo methods What hyper-parameters are, and what to do with them; an illustration with ridge regression {disk.frame} is epic {pmice}, an experimental package for missing data imputation in parallel using {mice} and {furrr} Building formulae Functional peace of mind Get basic summary statistics for all the variables in a data frame Getting {sparklyr}, {h2o}, {rsparkling} to work together and some fun with bash Importing 30GB of data into R with sparklyr Introducing brotools It's lists all the way down It's lists all the way down, part 2: We need to go deeper Keep trying that api call with purrr::possibly() Lesser known dplyr 0.7* tricks Lesser known dplyr tricks Lesser known purrr tricks Make ggplot2 purrr Mapping a list of functions to a list of datasets with a list of columns as arguments Predicting job search by training a random forest on an unbalanced dataset Teaching the tidyverse to beginners Why I find tidyeval useful tidyr::spread() and dplyr::rename_at() in action Easy peasy STATA-like marginal effects with R Functional programming and unit testing for data munging with R available on Leanpub How to use jailbreakr My free book has a cover! Work on lists of datasets instead of individual datasets by using functional programming Method of Simulated Moments with R New website! Nonlinear Gmm with R - Example with a logistic regression Simulated Maximum Likelihood with R Bootstrapping standard errors for difference-in-differences estimation with R Careful with tryCatch Data frame columns as arguments to dplyr functions Export R output to a file I've started writing a 'book': Functional programming and unit testing for data munging with R Introduction to programming econometrics with R Merge a list of datasets together Object Oriented Programming with R: An example with a Cournot duopoly R, R with Atlas, R with OpenBLAS and Revolution R Open: which is fastest? Read a lot of datasets at once with R Unit testing with R Update to Introduction to programming econometrics with R Using R as a Computer Algebra System with Ryacas

Lesser known dplyr 0.7* tricks

This blog post is an update to an older one I wrote in March. In the post from March, dplyr was at version 0.50, but since then a major update introduced some changes that make some of the tips in that post obsolete. So here I revisit the blog post from March by using dplyr 0.70.

Create new columns with mutate() and case_when()

The basic things such as selecting columns, renaming them, filtering, etc did not change with this new version. What did change however is creating new columns using case_when(). First, load dplyr and the mtcars dataset:

library("dplyr")
data(mtcars)

This was how it was done in version 0.50 (notice the ‘.$’ symbol before the variable ‘carb’):

mtcars %>%
    mutate(carb_new = case_when(.$carb == 1 ~ "one",
                                .$carb == 2 ~ "two",
                                .$carb == 4 ~ "four",
                                 TRUE ~ "other")) %>%
    head(5)
##    mpg cyl disp  hp drat    wt  qsec vs am gear carb carb_new
## 1 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4     four
## 2 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4     four
## 3 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1      one
## 4 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1      one
## 5 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2      two

This has been simplified to:

mtcars %>%
    mutate(carb_new = case_when(carb == 1 ~ "one",
                                carb == 2 ~ "two",
                                carb == 4 ~ "four",
                                TRUE ~ "other")) %>%
    head(5)
##    mpg cyl disp  hp drat    wt  qsec vs am gear carb carb_new
## 1 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4     four
## 2 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4     four
## 3 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1      one
## 4 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1      one
## 5 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2      two

No need for .$ anymore.

Apply a function to certain columns only, by rows, with purrrlyr

dplyr wasn’t the only package to get an overhaul, purrr also got the same treatment.

In the past, I applied a function to certains columns like this:

mtcars %>%
    select(am, gear, carb) %>%
    purrr::by_row(sum, .collate = "cols", .to = "sum_am_gear_carb") -> mtcars2
head(mtcars2)

Now, by_row() does not exist in purrr anymore, but instead a new package called purrrlyr was introduced with functions that don’t really fit inside purrr nor dplyr:

mtcars %>%
    select(am, gear, carb) %>%
    purrrlyr::by_row(sum, .collate = "cols", .to = "sum_am_gear_carb") -> mtcars2
head(mtcars2)
## # A tibble: 6 x 4
##      am  gear  carb sum_am_gear_carb
##   <dbl> <dbl> <dbl>            <dbl>
## 1     1     4     4                9
## 2     1     4     4                9
## 3     1     4     1                6
## 4     0     3     1                4
## 5     0     3     2                5
## 6     0     3     1                4

Think of purrrlyr as purrrs and dplyrs love child.

Using dplyr functions inside your own functions, or what is tidyeval

Programming with dplyr has been simplified a lot. Before version 0.70, one needed to use dplyr in conjuction with lazyeval to use dplyr functions inside one’s own fuctions. It was not always very easy, especially if you mixed columns and values inside your functions. Here’s the example from the March blog post:

extract_vars <- function(data, some_string){

  data %>%
    select_(lazyeval::interp(~contains(some_string))) -> data

  return(data)
}

extract_vars(mtcars, "spam")

More examples are available in this other blog post.

I will revisit them now with dplyr’s new tidyeval syntax. I’d recommend you read the Tidy evaluation vignette here. This vignette is part of the rlang package, which gets used under the hood by dplyr for all your programming needs. Here is the function I called simpleFunction(), written with the old dplyr syntax:

simpleFunction <- function(dataset, col_name){
  dataset %>%
    group_by_(col_name) %>%
    summarise(mean_mpg = mean(mpg)) -> dataset
  return(dataset)
}


simpleFunction(mtcars, "cyl")
## # A tibble: 3 x 2
##     cyl mean_mpg
##   <dbl>    <dbl>
## 1     4     26.7
## 2     6     19.7
## 3     8     15.1

With the new synax, it must be rewritten a little bit:

simpleFunction <- function(dataset, col_name){
  col_name <- enquo(col_name)
  dataset %>%
    group_by(!!col_name) %>%
    summarise(mean_mpg = mean(mpg)) -> dataset
  return(dataset)
}


simpleFunction(mtcars, cyl)
## # A tibble: 3 x 2
##     cyl mean_mpg
##   <dbl>    <dbl>
## 1     4     26.7
## 2     6     19.7
## 3     8     15.1

What has changed? Forget the underscore versions of the usual functions such as select_(), group_by_(), etc. Now, you must quote the column name using enquo() (or just quo() if working interactively, outside a function), which returns a quosure. This quosure can then be evaluated using !! in front of the quosure and inside the usual dplyr functions.

Let’s look at another example:

simpleFunction <- function(dataset, col_name, value){
  filter_criteria <- lazyeval::interp(~y == x, .values=list(y = as.name(col_name), x = value))
  dataset %>%
    filter_(filter_criteria) %>%
    summarise(mean_cyl = mean(cyl)) -> dataset
  return(dataset)
}


simpleFunction(mtcars, "am", 1)
##   mean_cyl
## 1 5.076923

As you can see, it’s a bit more complicated, as you needed to use lazyeval::interp() to make it work. With the improved dplyr, here’s how it’s done:

simpleFunction <- function(dataset, col_name, value){
  col_name <- enquo(col_name)
  dataset %>%
    filter((!!col_name) == value) %>%
    summarise(mean_cyl = mean(cyl)) -> dataset
  return(dataset)
}


simpleFunction(mtcars, am, 1)
##   mean_cyl
## 1 5.076923

Much, much easier! There is something that you must pay attention to though. Notice that I’ve written:

filter((!!col_name) == value)

and not:

filter(!!col_name == value)

I have enclosed !!col_name inside parentheses. I struggled with this, but thanks to help from @dmi3k and @_lionelhenry I was able to understand what was happening (isn’t the #rstats community on twitter great?).

One last thing: let’s make this function a bit more general. I hard-coded the variable cyl inside the body of the function, but maybe you’d like the mean of another variable? Easy:

simpleFunction <- function(dataset, group_col, mean_col, value){
  group_col <- enquo(group_col)
  mean_col <- enquo(mean_col)
  dataset %>%
    filter((!!group_col) == value) %>%
    summarise(mean((!!mean_col))) -> dataset
  return(dataset)
}


simpleFunction(mtcars, am, cyl, 1)
##   mean(cyl)
## 1  5.076923

«That’s very nice Bruno, but mean((cyl)) in the output looks ugly as sin» you might think, and you’d be right. It is possible to set the name of the column in the output using := instead of =:

simpleFunction <- function(dataset, group_col, mean_col, value){
  group_col <- enquo(group_col)
  mean_col <- enquo(mean_col)
  mean_name <- paste0("mean_", mean_col)[2]
  dataset %>%
    filter((!!group_col) == value) %>%
    summarise(!!mean_name := mean((!!mean_col))) -> dataset
  return(dataset)
}


simpleFunction(mtcars, am, cyl, 1)
##   mean_cyl
## 1 5.076923

To get the name of the column I added this line:

mean_name <- paste0("mean_", mean_col)[2]

To see what it does, try the following inside an R interpreter (remember to us quo() instead of enquo() outside functions!):

paste0("mean_", quo(cyl))
## [1] "mean_~"   "mean_cyl"

enquo() quotes the input, and with paste0() it gets converted to a string that can be used as a column name. However, the ~ is in the way and the output of paste0() is a vector of two strings: the correct name is contained in the second element, hence the [2]. There might be a more elegant way of doing that, but for now this has been working well for me.

That was it folks! I do recommend you read the Programming with dplyr vignette here as well as other blog posts, such as the one recommended to me by @dmi3k here.

Have fun with dplyr 0.70!