How to refer to variable instead of column with dplyr

前端 未结 1 839
一生所求
一生所求 2021-01-19 05:08

When using dplyr:filter, I often compute a local variable that holds the viable choices:

df <- as_tibble(data.frame(id=c(\"a\",\"b\"), val=1:6))
ids <-         


        
相关标签:
1条回答
  • 2021-01-19 05:44

    Unquote with !! to tell filter to look in the calling environment instead of the data frame:

    library(tidyverse)
    
    df <- data_frame(id = rep(c("a","b"), 3), val = 1:6)
    ids <- c("b", "c")
    
    df %>% filter(id %in% ids)
    #> # A tibble: 3 x 2
    #>      id   val
    #>   <chr> <int>
    #> 1     b     2
    #> 2     b     4
    #> 3     b     6
    
    df <- df %>% mutate(ids = "a")
    
    df %>% filter(id %in% ids)
    #> # A tibble: 3 x 3
    #>      id   val   ids
    #>   <chr> <int> <chr>
    #> 1     a     1     a
    #> 2     a     3     a
    #> 3     a     5     a
    
    df %>% filter(id %in% !!ids)
    #> # A tibble: 3 x 3
    #>      id   val   ids
    #>   <chr> <int> <chr>
    #> 1     b     2     a
    #> 2     b     4     a
    #> 3     b     6     a
    

    Of course, the better way to avoid such issues is to not put identically-named vectors in your global environment.

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