I can use tidyr::complete to expose missing rows.
For example, with the following data.frame, I can expose the missing third quarter easily:
suppressPackageStartupMessages({
library(dplyr)
library(tidyr)
})
set.seed(42)
df <- data.frame(
id = c(rep(1, 3), rep(2, 3)),
year = rep(2020, 3),
quarter = c(1, 2, 4),
data = runif(3)
)
df %>% complete(nesting(id, year), quarter = 1:4)
#> # A tibble: 8 x 4
#> id year quarter data
#> <dbl> <dbl> <dbl> <dbl>
#> 1 1 2020 1 0.915
#> 2 1 2020 2 0.937
#> 3 1 2020 3 NA
#> 4 1 2020 4 0.286
#> 5 2 2020 1 0.915
#> 6 2 2020 2 0.937
#> 7 2 2020 3 NA
#> 8 2 2020 4 0.286
Created on 2020-03-02 by the reprex package (v0.3.0)
Now, I want to create a wrapper for this specific use-case: it takes in a data.frame with at least these four columns and exposes the missing quarters.
That's easy enough, just wrap the complete call in a function:
expose <- function(df) {
complete(df, nesting(id, year), quarter = 1:4)
}
expose(df)
#> # A tibble: 8 x 4
#> id year quarter data
#> <dbl> <dbl> <dbl> <dbl>
#> 1 1 2020 1 0.915
#> 2 1 2020 2 0.937
#> 3 1 2020 3 NA
#> 4 1 2020 4 0.286
#> 5 2 2020 1 0.915
#> 6 2 2020 2 0.937
#> 7 2 2020 3 NA
#> 8 2 2020 4 0.286
However, the incoming data.frame might have other columns which are known to be constant for a given id. In this case, the function doesn't work, since it naturally sets those column to NA on the missing rows.
df <- data.frame(
id = c(rep(1, 3), rep(2, 3)),
name = c(rep("A", 3), rep("B", 3)),
country = c(rep("AU", 3), rep("BR", 3)),
year = rep(2020, 3),
quarter = c(1, 2, 4),
data = runif(3)
)
expose(df)
#> # A tibble: 8 x 6
#> id year quarter name country data
#> <dbl> <dbl> <dbl> <fct> <fct> <dbl>
#> 1 1 2020 1 A AU 0.830
#> 2 1 2020 2 A AU 0.642
#> 3 1 2020 3 <NA> <NA> NA
#> 4 1 2020 4 A AU 0.519
#> 5 2 2020 1 B BR 0.830
#> 6 2 2020 2 B BR 0.642
#> 7 2 2020 3 <NA> <NA> NA
#> 8 2 2020 4 B BR 0.519
To avoid this, I need to add those columns to the nesting call.
If it were only one column, I could add an argument to the function for the column's name, which I'd then use with nesting(..., .data[[colname]]). However, the .data pronoun doesn't work with vectors (.data[c("name1", "name2")] doesn't work).
So, how can I add multiple variable columns to the nesting call?