Reputation: 21387
Here is some code using complete
:
dat <- data.frame(a=c(1,NA), b=c(3,NA), val=c(20,30))
dat %>% complete(a, b, fill=list(val=0))
# A tibble: 4 x 3
a b val
<dbl> <dbl> <dbl>
1 1 3 20
2 1 NA 0
3 NA 3 0
4 NA NA 30
How do I make a function that takes the columns to complete? Here is a failed attempt:
foo_func <- function(dat, the_cols) {
dat %>% complete(all_of(the_cols), fill=list(val=0))
}
foo_func(dat, c('a', 'b'))
Error: Join columns must be present in data.
x Problem with `all_of(the_cols)`.
Here's another:
foo_func <- function(dat, the_cols) {
dat %>% complete(!!the_cols, fill=list(val=0))
}
foo_func(dat, c('a', 'b'))
Error: Join columns must be present in data.
x Problem with `<chr>`
I want the_cols
to be a character vector, because this is in an existing body of code that passes things around that way.
Upvotes: 4
Views: 242
Reputation: 887108
We could convert to sym
bols and use !!!
foo_func <- function(dat, the_cols) {
dat %>% complete(!!! rlang::syms(the_cols), fill=list(val=0))
}
-checking
foo_func(dat, c('a', 'b'))
# A tibble: 4 x 3
# a b val
# <dbl> <dbl> <dbl>
#1 1 3 20
#2 1 NA 0
#3 NA 3 0
#4 NA NA 30
Upvotes: 2