R – invalid argument to unary operator -error message – negative dplyr:: select with vector

dplyrr

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 in tidyselect

df_main %>%
    select(-one_of(keep.vec))
#  hanger dvd bookcase clock curtains wall
#1      1   1        1     1        1    1
#2      2   2        2     2        2    2
#3      3   3        3     3        3    3
#4      4   4        4     4        4    4
#5      5   5        5     5        5    5

Or another option is setdiff

df_main %>%
    select(setdiff(names(.), keep.vec))

which will also work outside the tidyverse

df_main[setdiff(names(df_main), keep.vec)]
Related Topic