1

我正在编写一个函数,该函数接受多个参数、字符串或字符串向量,这些参数与我想要过滤的属性相对应。我还想编写我的函数,以便当未指定过滤器属性时,它会被忽略,而其他过滤器属性可以工作。

为什么这种速记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' 
4

1 回答 1

0

你的函数的参数已经被引用为字符向量,你过滤的变量也是硬编码的。因此,我认为不需要quo. 你可以这样做:

library(dplyr)
library(datasets)

filterhec <- function(hair = NULL, eyecolor = NULL, sex = NULL) {
  hec <- as.data.frame(datasets::HairEyeColor)

  filter(
    hec,
    if (is.null(hair)) 1 else Hair == hair,
    if (is.null(eyecolor)) 1 else Eye %in% eyecolor,
    if (is.null(sex)) 1 else Sex == sex
  )
}

filterhec(hair = 'Black', eye = c('Brown', 'Blue'))
#>    Hair   Eye    Sex Freq
#> 1 Black Brown   Male   32
#> 2 Black  Blue   Male   11
#> 3 Black Brown Female   36
#> 4 Black  Blue Female    9
于 2018-11-04T16:40:22.467 回答