How to use a variable in dplyr::filter?

后端 未结 3 386
悲&欢浪女
悲&欢浪女 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: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)))
    

提交回复
热议问题