如何使用可能传入或不传入的几个函数参数过滤数据帧? (R; dplyr)

时间:2018-11-04 00:59:01

标签: r dplyr quosure

我正在编写一个函数,该函数带有多个参数,字符串或字符串向量,这些参数,字符串或向量与要过滤的属性相对应。我还想编写函数,以便在未指定过滤器属性的情况下,将其忽略,而其他过滤器属性也可以工作。

为什么使用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' 

1 个答案:

答案 0 :(得分: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