a_js12
a_js12

Reputation: 329

Subset Data Frame to Exclude 28 Different Months in R Using dplyr

I have a data frame consisting of monthly volumes beginning 2004-01-01 and ending 2019-12-01. I need to apply a filter that will delete rows that equal certain dates. My problem is that there's 28 dates I need to filter out and they arent consecutive. What I have right now works, but isn't efficient. I am using dplyr's filter function.

I currently have 28 variables, d1-d28, which are the dates that I would like filtered out and then I use

df<-data%>%dplyr::filter(Date!=d1 & Date!=d2 & Date!=d3 .......Date!=d28)

I would like to put the dates of interest, the d1-d28, into a data.frame and just reference the data.frame in my filter code.

I've tried:

df<-data%>%dplyr::filter(!Date %in% DateFilter) 

Where DateFilter is a data.frame with 1 column and 28 rows of the dates I want filtered, but I get an an error where it says the length of the objects don't match.

Is there any way I can do this with dplyr?

Upvotes: 0

Views: 265

Answers (1)

akrun
akrun

Reputation: 887108

Here, we may use filter_at

library(dplyr)
data %>%
      filter_at(vars(matches('^d\\d+$')), all_vars(Date != .))

Upvotes: 0

Related Questions