我正在尝试编写一个函数,以将一些quosure参数传递给内部dplyr::select
。但是,我希望能够在提供参数之后将某些条件应用于参数。在这种特殊情况下,因为选择不存在的列会产生错误,所以我希望函数检查调用方提供的列是否存在于通过tib
参数传递的数据框中,并删除在我之前不存在的列将quosure和unquoting运算符传递给select
。
问题在于,一旦某个物品进入了瓶盖内,我就不知道该如何操作了。我可以将名称转换为字符串,消除多余的名称,然后使用syms
将字符串的向量转换回符号,我认为在这种情况下可以使用,因为我要单独处理内部select
我希望在其中评估它们的数据框,但这基本上剥夺了使用quosure的所有好处,然后人为地再次提供它们,这似乎是round回和不雅。我想避免一种复杂的解决方案,这种解决方案在这种精确的情况下有效,但在下次没有提供任何有用的原理。
library(tidyverse)
tst_tb <- tibble(A = 1:10, B = 11:20, C=21:30, D = 31:40)
################################################################################
# strip() expects a non-anonymous dataframe, from which it removes the rows
# specified (as a logical vector) in remove_rows and the columns specified (as
# unquoted names) in remove_cols. It also prints a brief report; just the df
# name, length and width, and the remaining column names.
strip <- function(tib, remove_rows = FALSE, remove_cols = NULL){
remove_rows <- enquo(remove_rows)
remove_cols <- enquo(remove_cols)
tib_name <- deparse(substitute(tib))
out <- tib %>%
filter(! (!! remove_rows)) %>%
select(- !! remove_cols) %T>% (function(XX = .){
print(paste0(tib_name,": Length = ", nrow(XX), "; Width = ", ncol(XX)))
cat("\n")
cat(" Names: ", names(XX))
})
out
}
由于E
参数中的remove_cols
,下一行将不起作用。您不应该将E
看作是四五个中的一个名字,而是数百个中的十或二十个参数。
out_tb <- strip(tib = tst_df, remove_rows = (A < 3 | D > 36), remove_cols = c(C, D, E))
out_tb
所需的输出:
# A tibble: 4 x 2
A B
<int> <int>
1 3 13
2 4 14
3 5 15
4 6 16