I've been using a vector to positively subset a data frame, and it's working well. Now I'd like to use the same vector to negatively subset that data frame.
I get an error message (invalid argument to unary operator) but after googling I still don't understand what it means.
Thanks for any help!
# Starting point
df_main <- data.frame(coat=c(1:5),hanger=c(1:5),book=c(1:5),dvd=c(1:5),bookcase=c(1:5),
clock=c(1:5),bottle=c(1:5),curtains=c(1:5),wall=c(1:5))
df_keep <- data.frame(keep_var=c("coat","hanger","book","wall","bottle"),othvar=c("r","w","r","w",NA))
# Vector
library(dplyr)
keep.vec <- as.character(
(df_keep %>% dplyr::filter(is.na(othvar) | othvar == 'r'))$keep_var
)
# Attempts at using vector for negative subsetting
df_main %>% dplyr::select(-keep.vec)
df_main[-keep.vec, ]
Best Answer
We can wrap it with a helper function
one_of
intidyselect
Or another option is
setdiff
which will also work outside the
tidyverse