r dplyr filter with a dynamic variable name

后端 未结 2 1507
既然无缘
既然无缘 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:03

    Rather than referencing by name of column, just give it the entire column to filter by.

    x = data.frame(a = c(NA, 2, 3, 4))
    var_a <- "a"
    x %>% filter(!is.na(!!x[,var_a])) 
    

    Noticed I've just changed var_a to x[,var_a].

提交回复
热议问题