gpt4 book ai didi

r - 如何让 tidyr 完整地使用指定列的变量?

转载 作者:行者123 更新时间:2023-12-04 08:18:01 25 4
gpt4 key购买 nike

这是一些使用 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成为字符向量,因为这是在以这种方式传递事物的现有代码体中。

最佳答案

我们可以转换为 sym bolt 和使用 !!!

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

关于r - 如何让 tidyr 完整地使用指定列的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65620588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com