We can use the power of regex and filter in dplyr .
Assuming you have a filter variable consisting of n elements, where n also the number of columns of the target df dataframe.
Each element of the vector will filter the corresponding columns, and NA in the vector will take any value:
For instance:
filter <- c('democrat, 'y', 'y', NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)
will give as a result to all Democrats who voted y in the first two, and everything else.
filter <- c('republican', 'y', 'n', NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA) filter <- toString(filter) %>% gsub(pattern = 'NA', x = ., replacement = '.+') df %>% unite(string, Class:V16, sep = ', ', remove = F) %>% filter(grepl(x = string, pattern = filter)) %>% select(-string) # Class V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 # 1 republican ynnyynyyynnyyyny # 2 republican ynyyynynyynnyyny # 3 republican ynyyyyyynynynyyy # 4 republican ynyyyyyynyyynyyy # 5 republican ynnnnnyyyynnnyny