# Creating empty data frames with dfTemplate() and dfTemplateMatch()

#### February 3, 2019

Creating a data frame is fairly simple but when you need to create a large empty data frame with columns that have different classes it takes several command lines. A few days ago, I decided to write a function to simplify this operation and I came to realize that such a function would actually be very useful to ease the row binding of data frames whose column names partially match. How so? This post is meant to answer this question!

## inSilecoMisc

First of all, the functions I am using in this post are available in inSilecoMisc which is an R package where we gathered the miscellaneous functions we wrote and deem worth sharing on GitHub. So the first step to reproduce the examples below is to install inSilecoMisc which is straightforward with the devtools :

library(devtools)
install_github("inSileco/inSilecoMisc")

library(inSilecoMisc)

In this post, I’ll exemplify how to use dfTemplate() and dfTemplateMatch() but if you are interested in other functions in the packages, check out the tour vignette.

## Generating empty data frames efficiently

Let’s start with dfTemplate() that creates a data frame with a specific number of columns.

df1 <- dfTemplate(cols = 2)
df1
#R>    Var1 Var2
#R>  1   NA   NA
class(df1)
#R>  [1] "data.frame"

By default, the data frame created has only 1 row and the columns are filled out with NA. This can readily be changed using arguments nrows and fill.

df2 <- dfTemplate(2, nrows = 4, fill = 0)
df2
#R>    Var1 Var2
#R>  1    0    0
#R>  2    0    0
#R>  3    0    0
#R>  4    0    0
df3 <- dfTemplate(cols = 2, nrows = 3, fill = "")
df3
#R>    Var1 Var2
#R>  1
#R>  2
#R>  3

Columns classes are determined by fill:

class(df1[, 1])
class(df2[, 1])
class(df3[, 1])
#R>  [1] "logical"
#R>  [1] "numeric"
#R>  [1] "character"

And col_classes is used to changed these classes:

df4 <- dfTemplate(cols = 2, col_classes = "character")
class(df4[, 1])
class(df4[, 2])
#R>  [1] "character"
#R>  [1] "character"

Arguments fill and col_classes can be vectors that specify content and class for every columns:

df5 <- dfTemplate(2, 5, col_classes = c("character", "numeric"), fill = c("", 5))
df5
class(df5[, 1])
class(df5[, 2])
#R>    Var1 Var2
#R>  1         5
#R>  2         5
#R>  3         5
#R>  4         5
#R>  5         5
#R>  [1] "character"
#R>  [1] "numeric"

Another useful feature of dfTemplate() is that column names of the data frame to be created can be passed as first argument (cols) :

df5 <- dfTemplate(c("category", "value"))

So, now you are able to create custom data frames with a set of column names!

nms <- LETTERS[1:10]
df6 <- dfTemplate(nms, 10, fill = tolower(nms))
df6
#R>     A B C D E F G H I J
#R>  1  a b c d e f g h i j
#R>  2  a b c d e f g h i j
#R>  3  a b c d e f g h i j
#R>  4  a b c d e f g h i j
#R>  5  a b c d e f g h i j
#R>  6  a b c d e f g h i j
#R>  7  a b c d e f g h i j
#R>  8  a b c d e f g h i j
#R>  9  a b c d e f g h i j
#R>  10 a b c d e f g h i j

## How to flexiblyrbind a list of data frames

Sometimes we need to rbind data frames that do not have all the columns the final data frame must contain. In such case, we first need to append the missing columns because otherwise the default rbind function won’t work. Another solution is to use a package that has a function that do so. For instance, rbind.fill() from the plyr package allows to perform such flexible rbind. Also, the package data.table includes a rbind() method for data.table objects that handles such situation (see this answer on ). In this last section, I would like to show how to rbind data frames flexibly with dfTemplateMatch() that is written in base R.

Let me first introduces dfTemplateMatch(). This function takes a data frame as the first argument (x) and the second argument (y) could be another data frame or a vector of character strings. Based on x and y, dfTemplateMatch() creates a data frame that has the same number of rows as x and add columns for all names found in y that are not found in x. Before calling dfTemplateMatch() I create two data frames :

df7 <- df6[1:5, 1:4]
df7
#R>    A B C D
#R>  1 a b c d
#R>  2 a b c d
#R>  3 a b c d
#R>  4 a b c d
#R>  5 a b c d
df8 <- df6[4:6]
df8
#R>     D E F
#R>  1  d e f
#R>  2  d e f
#R>  3  d e f
#R>  4  d e f
#R>  5  d e f
#R>  6  d e f
#R>  7  d e f
#R>  8  d e f
#R>  9  d e f
#R>  10 d e f

Now I use dfTemplateMatch() to create a third data frame based on two other:

dfTemplateMatch(df7, df8)
#R>    A B C D  E  F
#R>  1 a b c d NA NA
#R>  2 a b c d NA NA
#R>  3 a b c d NA NA
#R>  4 a b c d NA NA
#R>  5 a b c d NA NA

As expected, the output has 5 rows as df6 and columns that are not in df6 but in df7 has been appended to df6. It is possible to use arguments fill and col_classes to custom the columns added.

dfTemplateMatch(df7, df8, fill = 1, col_classes = "numeric")
#R>    A B C D E F
#R>  1 a b c d 1 1
#R>  2 a b c d 1 1
#R>  3 a b c d 1 1
#R>  4 a b c d 1 1
#R>  5 a b c d 1 1

And there is an argument yonly that allows the user to keep only names of y (when yonly = TRUE).

dfTemplateMatch(df7, df8, yonly = TRUE, fill = 1, col_classes = "numeric")
#R>    D E F
#R>  1 d 1 1
#R>  2 d 1 1
#R>  3 d 1 1
#R>  4 d 1 1
#R>  5 d 1 1

Now let me show you how to rbind() a specific subset of columns of a list of data frame that may or may not have these columns. Let me start by creating a list of data frames.

lsdf <- apply(
replicate(5, sample(nms, 5)),
2,
function(x) dfTemplate(x, nrows = 5, fill = tolower(x))
)
lsdf
#R>  [[1]]
#R>    E A G I J
#R>  1 e a g i j
#R>  2 e a g i j
#R>  3 e a g i j
#R>  4 e a g i j
#R>  5 e a g i j
#R>
#R>  [[2]]
#R>    F J A E C
#R>  1 f j a e c
#R>  2 f j a e c
#R>  3 f j a e c
#R>  4 f j a e c
#R>  5 f j a e c
#R>
#R>  [[3]]
#R>    H C A G D
#R>  1 h c a g d
#R>  2 h c a g d
#R>  3 h c a g d
#R>  4 h c a g d
#R>  5 h c a g d
#R>
#R>  [[4]]
#R>    J D G F E
#R>  1 j d g f e
#R>  2 j d g f e
#R>  3 j d g f e
#R>  4 j d g f e
#R>  5 j d g f e
#R>
#R>  [[5]]
#R>    I C F H J
#R>  1 i c f h j
#R>  2 i c f h j
#R>  3 i c f h j
#R>  4 i c f h j
#R>  5 i c f h j

So the goal here is to create a data frame that contains only the five first columns, i.e. A, B, C, D, E, the remaining columns must be discarded and when one selected column is missing, it must be added (filled out with NA). To do so, I simply need to call dfTemplateMatch():

lsdf2 <- lapply(lsdf, dfTemplateMatch, LETTERS[1:5], yonly = TRUE)
lsdf2
#R>  [[1]]
#R>    E A  B  C  D
#R>  1 e a NA NA NA
#R>  2 e a NA NA NA
#R>  3 e a NA NA NA
#R>  4 e a NA NA NA
#R>  5 e a NA NA NA
#R>
#R>  [[2]]
#R>    A E C  B  D
#R>  1 a e c NA NA
#R>  2 a e c NA NA
#R>  3 a e c NA NA
#R>  4 a e c NA NA
#R>  5 a e c NA NA
#R>
#R>  [[3]]
#R>    C A D  B  E
#R>  1 c a d NA NA
#R>  2 c a d NA NA
#R>  3 c a d NA NA
#R>  4 c a d NA NA
#R>  5 c a d NA NA
#R>
#R>  [[4]]
#R>    D E  A  B  C
#R>  1 d e NA NA NA
#R>  2 d e NA NA NA
#R>  3 d e NA NA NA
#R>  4 d e NA NA NA
#R>  5 d e NA NA NA
#R>
#R>  [[5]]
#R>    C  A  B  D  E
#R>  1 c NA NA NA NA
#R>  2 c NA NA NA NA
#R>  3 c NA NA NA NA
#R>  4 c NA NA NA NA
#R>  5 c NA NA NA NA

And now I can seamlessly rbind() the list lsdf2!

do.call(rbind, lsdf2)
#R>        E    A  B    C    D
#R>  1     e    a NA <NA> <NA>
#R>  2     e    a NA <NA> <NA>
#R>  3     e    a NA <NA> <NA>
#R>  4     e    a NA <NA> <NA>
#R>  5     e    a NA <NA> <NA>
#R>  6     e    a NA    c <NA>
#R>  7     e    a NA    c <NA>
#R>  8     e    a NA    c <NA>
#R>  9     e    a NA    c <NA>
#R>  10    e    a NA    c <NA>
#R>  11 <NA>    a NA    c    d
#R>  12 <NA>    a NA    c    d
#R>  13 <NA>    a NA    c    d
#R>  14 <NA>    a NA    c    d
#R>  15 <NA>    a NA    c    d
#R>  16    e <NA> NA <NA>    d
#R>  17    e <NA> NA <NA>    d
#R>  18    e <NA> NA <NA>    d
#R>  19    e <NA> NA <NA>    d
#R>  20    e <NA> NA <NA>    d
#R>  21 <NA> <NA> NA    c <NA>
#R>  22 <NA> <NA> NA    c <NA>
#R>  23 <NA> <NA> NA    c <NA>
#R>  24 <NA> <NA> NA    c <NA>
#R>  25 <NA> <NA> NA    c <NA>

#### Voilà! This is what I call a flexiblerbind! I hope you’ll find this helpful! 💥

Session info
sessionInfo()
#R>  R version 4.2.2 (2022-10-31)
#R>  Platform: x86_64-pc-linux-gnu (64-bit)
#R>  Running under: Ubuntu 22.04.1 LTS
#R>
#R>  Matrix products: default
#R>
#R>  locale:
#R>   [1] LC_CTYPE=C.UTF-8       LC_NUMERIC=C           LC_TIME=C.UTF-8
#R>   [4] LC_COLLATE=C.UTF-8     LC_MONETARY=C.UTF-8    LC_MESSAGES=C.UTF-8
#R>  [10] LC_TELEPHONE=C         LC_MEASUREMENT=C.UTF-8 LC_IDENTIFICATION=C
#R>
#R>  attached base packages:
#R>  [1] stats     graphics  grDevices utils     datasets  methods   base
#R>
#R>  other attached packages:
#R>  [1] inSilecoMisc_0.7.0.9000 inSilecoRef_0.0.1.9000
#R>
#R>  loaded via a namespace (and not attached):
#R>   [1] tidyselect_1.2.0  xfun_0.35         bslib_0.4.1       vctrs_0.5.1
#R>   [5] generics_0.1.3    miniUI_0.1.1.1    htmltools_0.5.4   yaml_2.3.6
#R>   [9] utf8_1.2.2        rlang_1.0.6       later_1.3.0       pillar_1.8.1
#R>  [13] jquerylib_0.1.4   httpcode_0.3.0    glue_1.6.2        DBI_1.1.3
#R>  [17] lifecycle_1.0.3   plyr_1.8.8        stringr_1.5.0     blogdown_1.15
#R>  [21] htmlwidgets_1.5.4 evaluate_0.18     knitr_1.41        fastmap_1.1.0
#R>  [25] httpuv_1.6.6      curl_4.3.3        fansi_1.0.3       Rcpp_1.0.9
#R>  [29] xtable_1.8-4      promises_1.2.0.1  backports_1.4.1   DT_0.26
#R>  [33] cachem_1.0.6      jsonlite_1.8.4    rcrossref_1.2.0   mime_0.12
#R>  [37] digest_0.6.30     stringi_1.7.8     bookdown_0.30     dplyr_1.0.10
#R>  [41] shiny_1.7.3       bibtex_0.5.0      cli_3.4.1         tools_4.2.2
#R>  [45] magrittr_2.0.3    sass_0.4.4        tibble_3.1.8      RefManageR_1.4.0
#R>  [49] crul_1.3          crayon_1.5.2      pkgconfig_2.0.3   ellipsis_0.3.2
#R>  [53] xml2_1.3.3        timechange_0.1.1  lubridate_1.9.0   assertthat_0.2.1
#R>  [57] rmarkdown_2.18    httr_1.4.4        R6_2.5.1          compiler_4.2.2

Comment with Disqus