使用动态变量名称和完成范围从函数内部完成变量

问题描述 投票:0回答:1

我想创建一个函数来完成具有给定范围的变量,两者都作为参数传递给函数。

# 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 转换为因子可能会更好,但我真的很想知道如何在没有因子的情况下做到这一点。

r dplyr
1个回答
0
投票
test <- function(data, variable, range, fill) {  
  
  # no quotes around {{ variable }}
  # use :=
  tmp <- data %>% complete({{ variable }} := range, fill = fill)
  
  return(tmp)
}

# And the way I want to call the function:  
z %>% test(g1, 1:5, fill = list(n = 0, gender = 'f'))

# A tibble: 5 × 3
     g1 gender     n
  <dbl> <chr>  <dbl>
1     1 f          0
2     2 f          3
3     3 f          2
4     4 f          8
5     5 f          3

tidyeval
习惯起来肯定很奇怪,但通过练习就开始有意义了。

© www.soinside.com 2019 - 2024. All rights reserved.