r dplyr filter with a dynamic variable name

后端 未结 2 1505
既然无缘
既然无缘 2021-01-12 14:55

I am trying to select only the rows without NAs:

library(dplyr)
x = data.frame(a = c(NA, 2, 3, 4))
var_a <- \"a\"
# This works:
x %>% filter(!is.na(a))         


        
2条回答
  •  梦谈多话
    2021-01-12 15:14

    It is a string, so we can convert to symbol with sym and then use !!

    x %>% 
       filter(!is.na(!!rlang::sym(var_a)))
    #  a
    #1 2
    #2 3
    #3 4
    

    Or another option is to specify the object in filter_at and then do the filtering

    x %>% 
       filter_at(var_a, all_vars(!is.na(.)))
    #  a
    #1 2
    #2 3
    #3 4
    

提交回复
热议问题