Motivation
Column operations
Add
Modify
Remove
Benchmark
Summary
Motivation
The dplyr functions select and mutate nowadays are commonly applied to perform data.frame column operations, frequently combined with magrittrs forward %__% pipe. While working well interactively, however, these methods often would require additional checking if used in “serious” code, for example, to catch column name clashes.
In principle, the container package provides a dict-class (resembling Pythons dict type), which allows to cover these issues more easily. In its very recent update, the container package for this reason gained an S3 method interface plus functions to convert back and forth between dict and data.frame. This can be used to extend the set of data.frame column operations and in this post I will show how and when they can serve as a useful alternative to mutate and select.
To keep matters simple, we use a tiny data table.
data % as.dict() %__% add(&quot;ID&quot;, 1:n) %__% as.data.frame()## x y ID## 1 0.2 a 1## 2 0.5 b 2
The intended add-operation is stated more clearly, but on the downside we also had to add some overhead. Of course, since this has to be done only at the beginning and at the end of the pipe, it will be less of an issue if multiple dict-operations are performed in between. Next, instead of ID, let’s add another numeric column y, which happens to “name-clash” with the already existing column.
data %__% mutate(y = rnorm(n))## x y## 1 0.2 1.5295729## 2 0.5 0.4821652
Ooops - we have accidently overwritten the initial y-column. While this was easy to see here, it may not if the data.frame has a lot of columns or if column names are created automatically as part of some script. To catch this, usually some overhead is required, too.
if (&quot;y&quot; %in% colnames(data)) { stop(&quot;column y already exists&quot;)} else { data %__% mutate(y = rnorm(n))}## Error in eval(expr, envir, enclos): column y already exists
Let’s see the dict-operation in comparison.
data %__% as.dict() %__% add(&quot;y&quot;, rnorm(n)) %__% as.data.frame()## Error in x$add(key, value): key 'y' already in Dict
The name clash is catched by default and the overhead does not look so silly anymore. As a bonus, the error message still provides information about the originally intended add-operation.
Modify
If the intend was indeed to overwrite the value, the dict-function setval can be used.
data %__% as.dict() %__% setval(&quot;y&quot;, rnorm(n)) %__% as.data.frame()## x y## 1 0.2 0.5315501## 2 0.5 -0.1573612
As we saw above, if a column does not exist, mutate silently creates it for you. If this is not what you want, which means, you want to make sure something is overwritten, again, a workaround is needed.
if (&quot;ID&quot; %in% colnames(data)) { data %__% mutate(ID = 1:n) } else { stop(&quot;column ID not in data.frame&quot;)}## Error in eval(expr, envir, enclos): column ID not in data.frame
Once again, the workaround is already “built-in” in the dict-framework.
data %__% as.dict() %__% setval(&quot;ID&quot;, 1:n) %__% as.data.frame()## Error in x$set(key, value, add): key 'ID' not in Dict
After all, the intend of the mutate function actually would be something like: overwrite a column, or, create it if it does not exist. If desired, this behaviour can be expressed within the dict-framework as well.
data %__% as.dict() %__% setval(&quot;ID&quot;, 1:n, add=TRUE) %__% as.data.frame()## x y ID## 1 0.2 a 1## 2 0.5 b 2
Remove
A common tidyverse approach to remove a column is based on the select function. One corresponding dict-function is remove.
data %__% select(-&quot;y&quot;)## x## 1 0.2## 2 0.5data %__% as.dict() %__% remove(&quot;y&quot;) %__% as.data.frame()## x## 1 0.2## 2 0.5
Let’s see what happens if the column does not exist in the first place.
data %__% select(-&quot;ID&quot;)## Error: Unknown column `ID`data %__% as.dict() %__% remove(&quot;ID&quot;) %__% as.data.frame()## Error in x$remove(key): key 'ID' not in Dict
Again, we obtain a slightly more informative error message with dict. Assume we want the column to be removed if it exist but otherwise silently ignore the command, for example:
if (&quot;ID&quot; %in% colnames(data)) { data %__% select(-&quot;ID&quot;) }
You may have expected this by now - the dict-framework provides a straigh-forward solution, namely, the discard function:
data %__% as.dict() %__% discard(&quot;ID&quot;) %__% discard(&quot;y&quot;) %__% add(&quot;z&quot;, c(&quot;Hello&quot;, &quot;World&quot;)) %__% as.data.frame()## x z## 1 0.2 Hello## 2 0.5 World
Benchmark
The required additional code lines are limited but what about the computational overhead? To examine this, we benchmark some column operations using the famous ‘iris’ data set. As a hallmark reference we will also bring the data.table framework to the competition.
set.seed(123)library(microbenchmark)library(ggplot2)library(data.table)data % select(-Sepal.Width), dict = data %__% as.dict() %__% add(&quot;ID&quot;, 1:n) %__% setval(., &quot;Species&quot;, as.character(.$get(&quot;Species&quot;))) %__% remove(&quot;Sepal.Width&quot;) %__% as.data.frame(), `[.data.table` = data %__% as.data.table() %__% .[, ID := 1:n] %__% .[, Species := as.character(Species)] %__% .[, Sepal.Width := NULL])autoplot(bm) + theme_bw()
Somewhat surprisingly maybe, the dict-implementation is closer to the data.table than to the dplyr performance. Let’s examine each operation in more detail.
bm % as.data.frame(), `[.data.table` = data %__% as.data.table() %__% .[, ID := 1:n] %__% .[, Species := as.character(Species)] %__% .[, Sepal.Width := NULL], data.table.set = data %__% as.data.table() %__% set(., j= &quot;ID&quot;, value = 1:n) %__% set(., j = &quot;Species&quot;, value = as.character(.[[&quot;Species&quot;]])) %__% set(., j = &quot;Sepal.Width&quot;, value = NULL))autoplot(bm) + theme_bw()
This puts things back into perspective, I guess :) It might also be interesting to know, how much of the computation time is spent on the non-standard evaluation part of the dplyr and [.data.table implementation, but that’s probably a topic on its own.
Summary
Accidently overwriting existing data columns leads to nasty bugs. The presented workflow allows to increase both reliability and precision of standard data frame column manipulation at very little cost. The intended column operations can be expressed more clearly and, in case of failures, informative error messages are provided by default. As a result, the dict-framework may serve as a useful supplement to “interactive piping”.