1) rlang/tidyreval用于!!!syms(notnum_names)
插入变量名作为complete
参数。Fill
只是一个普通的列表,不需要 rlang/tidyeval 计算。
library(dplyr)
library(tidyr)
library(rlang)
completeDF <- function(data) {
is_num <- sapply(data, is.numeric)
num_names <- names(data)[ is_num ]
notnum_names <- names(data)[ !is_num ]
fill <- Map(function(x) 0, num_names)
data %>% complete(!!!syms(notnum_names), fill = fill)
}
DF <- data.frame(a = c("A", "B", "B"), b = c("a", "a", "b"), c = 1:3) # test data
completeDF(DF)
给予:
# A tibble: 4 x 3
a b c
<fctr> <fctr> <dbl>
1 A a 1
2 A b 0
3 B a 2
4 B b 3
这是修改后的问题的原始代码以使其工作。更改的行在每行末尾都用## 标记。
completeDf <- function(df){
vars <- names(df)
chVars <- vars[!(sapply(df, is.numeric))]
nmVars <- vars[!(vars %in% chVars)]
symsChVars <- rlang::syms(chVars) ##
nmList <- vector("list", length(nmVars))
nmList <- setNames(lapply(nmList, function(x) 0), nmVars) ##
# quoNmVars <- quos(nmList ##
df %>% ##
complete(!!!symsChVars, fill = nmList) ##
}
completeDf(DF)
2) wrapr rlang/tidyeval 的替代方案是 wrapr 包。
此处的代码与 (1) 中的代码相同,只是我们使用library(wrapr)
了代替,library(rlang)
并且最后一行 ofcompleteDF
被替换为let
语句给completeDF2
.
library(dplyr)
library(tidyr)
library(wrapr)
completeDF2 <- function(data) {
is_num <- sapply(data, is.numeric)
num_names <- names(data)[ is_num ]
notnum_names <- names(data)[ !is_num ]
fill <- Map(function(x) 0, num_names)
let(c(NOTNUM = toString(notnum_names)),
data %>% complete(NOTNUM, fill = fill),
strict = FALSE,
subsMethod = "stringsubs")
}
completeDF2(DF)
更新:修复和改进。添加包装方法。