Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

r dplyr filter with a dynamic variable name

Tags:

r

filter

dplyr

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))
# That works too:
var_a <- quo(a)
x %>% filter(!is.na(!!var_a))
# But this doesn't work:
var_a <- "a"
x %>% filter(!is.na(!!var_a))

What should I change in the last line for it to work? Because I have to work with var_a <- "a". Thank you very much!

like image 452
user3245256 Avatar asked Apr 12 '18 01:04

user3245256


2 Answers

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
like image 71
akrun Avatar answered Sep 22 '22 07:09

akrun


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].

like image 41
LachlanO Avatar answered Sep 20 '22 07:09

LachlanO