I would like to filter a data frame to leave only the complete cases based on selected columns. This is easy to do with NSE filter()
:
library(dplyr)
dd <- data.frame(
id = 1:4,
var1 = c(1, 2, NA, 4),
var2 = c(1, NA, 3, 4),
var3 = c(1, NA, NA, NA))
dd1 <- dd %>% filter(complete.cases(var1, var2))
dd1
#> id var1 var2 var3
#> 1 1 1 1 1
#> 2 4 4 4 NA
However I'm running in to a wall in trying to produce an SE version of this operation to which I may pass the quoted names of columns.
library(lazyeval)
filtered_cols <- c("var1", "var2")
dots <- interp(~complete.cases(x), .values = list(x = filtered_cols))
dd2 <- dd %>% filter_(.dots = dots)
#> Error in eval(substitute(expr), envir, enclos): incorrect length (2), expecting: 4
str(dots)
#> Class 'formula' language ~complete.cases(c("var1", "var2"))
#> ..- attr(*, ".Environment")=<environment: R_GlobalEnv>
Unfortunately, filtered_cols
is getting parsed as a character vector. How can I get interp()
to treat filtered_cols
as multiple column names to be passed to complete.cases()
?
This is what uqs()
is for, but you have to use the newer f_interp()
:
library(lazyeval)
filtered_cols <- c("var1", "var2")
filtered_col_names <- lapply(filtered_cols, as.name)
dots <- f_interp(~complete.cases(uqs(filtered_col_names)))
dd2 <- dd %>% filter_(.dots = dots)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With