我想创建一个函数,完成具有给定范围的变量,并将其作为参数传递给函数。
# The sample data frame. The colum g1 normaly has the range 1 to 5, but in this
# filtered subset it only has the range 2 to 5:
z <- data.frame(gender = c('f','f','f','f'), g1 = c(2,3,4,5), n = c(3,2,8,3))
# The function:
test <- function(data, variable, range) {
# thats what i actually want to do
#tmp <- data %>% complete(g1 = 1:5)
# and thats my not working attempt
tmp <- data %>% complete("{{variable}}" = range)
return(tmp)
}
# And the way I want to call the function:
z %>% test(g1, 1:5)
这产生了我想要的结果,但没有我的功能
z %>% complete(gender, g1 = 1:5, fill = list(n = 0))
gender g1 n
<chr> <dbl> <dbl>
1 f 1 0
2 f 2 3
3 f 3 2
4 f 4 8
5 f 5 3
将 g1 转换为因子可能更好,但我真的很想知道如何在没有因子的情况下做到这一点。
tidyeval
习惯起来肯定会很奇怪,但随着练习就会开始变得有意义。你可以在这里找到一份 tidyeval 备忘单(PDF)