How to use a variable in dplyr::filter?

后端 未结 3 387
悲&欢浪女
悲&欢浪女 2020-12-05 10:29

I have a variable with the same name as a column in a dataframe:

df <- data.frame(a=c(1,2,3), b=c(4,5,6))
b <- 5

I want to get the ro

相关标签:
3条回答
  • 2020-12-05 11:03

    You could use the get function to fetch the value of the variable from the environment.

    df %>% filter(b == get("b")) # Note the "" around b
    
    0 讨论(0)
  • 2020-12-05 11:17

    As a general solution, you can use the SE (standard evaluation) version of filter, which is filter_. In this case, things get a bit confusing because your are mixing a variable and an 'external' constant in a single expression. Here is how you do that with the interp function:

    library(lazyeval)
    df %>% filter_(interp(~ b == x, x = b))
    

    If you would like to use more values in b you can write:

    df %>% filter_(interp(~ b == x, .values = list(x = b)))
    
    0 讨论(0)
  • 2020-12-05 11:24

    Recently I have found this to be an elegant solution to this problem, although I'm just starting to wrap my head around how it works.

    df %>% filter(b == !!b)

    which is syntactic sugar for

    df %>% filter(b == UQ(b))

    A high-level sense of this is that the UQ (un-quote) operation causes its contents to be evaluated before the filter operation, so that it's not evaluated within the data.frame.

    This is described in this chapter of Advanced R, on 'quasi-quotation'. This chapter also includes a few solutions to similar problems related to non-standard evaluation (NSE).

    0 讨论(0)
提交回复
热议问题