I want to make a function that would apply tidyr::complete to all non-numeric columns of an R data.frame. Value zero should be inserted to the new value rows. I understand that this requires standard evaluation solution, but I've thus far had no success.
Here is what I have thus far:
completeDf <- function(df){
vars <- names(df)
chVars <- vars[!(sapply(df, is.numeric))]
nmVars <- vars[!(vars %in% chVars)]
quoChVars <- quos(chVars)
nmList <- vector("list", length(nmVars))
nmList <- setNames(lapply(nmList, function(x) x <- 0), nmVars)
quoNmVars <- quos(nmList)
df <- df %>%
complete(!!!quoChVars, fill = !!!quoNmVars)
}
Any idea of how to make this work?
1) rlang/tidyreval Use
!!!syms(notnum_names)to insert the variable names ascompletearguments.Fillis just an ordinary list and no rlang/tidyeval computations are needed for it.giving:
Here is the original code from the question modified to make it work. The changed lines are marked with ## at the end of each.
2) wrapr An alternative to rlang/tidyeval is the wrapr package.
The code here is the same as in (1) except we use
library(wrapr)instead oflibrary(rlang)and the last line ofcompleteDFis replaced with aletstatement givingcompleteDF2.Updates: Fixes and improvements. Add wrapr approach.