r语言 - 如何让整洁完成与指定列的变量一起使用?

  • 本文关键字:变量 一起 r语言 r tidyr
  • 更新时间 :
  • 英文 :


以下是一些使用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

如何生成一个函数来完成列?这是一次失败的尝试:

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)`.

这是另一个:

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>`

我希望the_cols是一个字符向量,因为它位于以这种方式传递信息的现有代码体中。

我们可以转换为symbols并使用!!!

foo_func <- function(dat, the_cols) {
dat %>% complete(!!! rlang::syms(the_cols), fill=list(val=0))
}

-检查

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

最新更新