我正在编写一个函数,该函数接受多个参数、字符串或字符串向量,这些参数与我想要过滤的属性相对应。我还想编写我的函数,以便当未指定过滤器属性时,它会被忽略,而其他过滤器属性可以工作。
为什么这种速记quo
不能以这种方式工作,我该如何改变它才能做到这一点?
library(dplyr); library(datasets)
filterhec <- function(hair = '', eyecolor = '', sex = '') {
hec <- as.data.frame(datasets::HairEyeColor)
# Filter condition variable, which changes depending on parameters
fcond <- quo(
(ifelse(hair == '', 1, Hair == hair)) &
(ifelse(all(eyecolor == ''), 1, Eye %in% eyecolor)) &
(ifelse(sex == '', 1, Sex == sex)))
filter(hec, !!fcond)
}
filterhec(hair = 'Black', eye = c('Brown', 'Blue'))
# Hair Eye Sex Freq
# 1 Black Brown Male 32
# 2 Brown Brown Male 53
# 3 Red Brown Male 10
# 4 Blond Brown Male 3
# 5 Black Blue Male 11
# 6 Brown Blue Male 50
# 7 Red Blue Male 10
# 8 Blond Blue Male 30
# 9 Black Hazel Male 10
#
# ^Expected dataframe where Hair is always 'Black' and Eye is 'Brown' or 'Blue'