簡體   English   中英

R / dplyr /字符串中的復數過濾器

[英]R / dplyr / complex filter in function by string

我正在嘗試將具有多個參數的過濾器作為字符串傳遞給函數中的dplyr :: filter。 到目前為止,我所看到的答案都涉及單個過濾器參數,而不是多個過濾器參數。

例:

myfil <- function(df, fil) {
    quo_fil <- enquo(fil)
    df <- filter(df, !! quo_fil)
    df 
}

set.seed(25)
df <- data.frame(a = sample(10, 10), b = sample(10, 10), c = sample(10, 10))

#works
filter(df, a > 3 & b > 2 & c < 8)

  a  b c
1 5  4 1
2 7 10 5
3 9  5 2
4 6  6 3

# does not work
f <- "a > 3 & b > 2 & c < 8"

myfil(df, f)

問題不在於您正在使用多個條件。 您可以看到只有一個條件就會遇到相同的問題。 問題是enquo期望裸表達式而不是字符串。 因此,這將返回預期結果:

myfil(df, a > 3 & b > 2 & c < 8)

  a  b c
1 5  4 1
2 7 10 5
3 9  5 2
4 6  6 3

如果要使用字符串,可以使用rlang::parse_expr將字符串轉換為!!的表達式!! 跟...共事:

myfil <- function(df, fil) {
  quo_fil <- rlang::parse_expr(fil)
  filter(df, !!quo_fil)
}

f <- "a > 3 & b > 2 & c < 8"
myfil(df, f)

  a  b c
1 5  4 1
2 7 10 5
3 9  5 2
4 6  6 3

根據答案,您只需將普通字符串傳遞給filter_函數即可,並且效果很好。

myfil <- function(df, fil) {
   df <- filter_(df, fil)
   df   
}

我的結果:

> myfil(df, 'a > 3 & b > 2 & c < 8')
  a b c
1 8 9 7

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM