raghav
raghav

Reputation: 533

Subset data frame based on condition of multiple months and years in R?

The attached is the data frame I am dealing with.

data frame

The first column in the data frame is the Date. I have to subset data frame based on condition on multiple months and years. For example, I want all July and September months data for the years 2005 and 2006.

I tried following code:

output <- subset(df, format.Date(Date, "%m")==c("07", "09") & format.Date(Date, "%Y")==c("2005","2006"))

The above code results the unexpected output.

I found posts regarding this problem but those were only for single month and year.

Upvotes: 1

Views: 949

Answers (1)

user13653858
user13653858

Reputation:

If you don't mind installing tidyverse package, you can use this simple filtering:

library(tidyverse)
library(lubridate)  # should come with tidyverse, no need to install it separately

# filter July and September data in 2005 and 2006
output <- df %>%
    filter(year(Date) %in% c(2005, 2006) & month(Date) %in% c(7, 9))

If you want to use base R, this should work as well:

output <- subset(df, format(Date, "%m") %in% c("07", "09") & format(Date, "%Y") %in% c("2005", "2006"))

in case that class of df$Date column is "Date".

Upvotes: 1

Related Questions