ShwyGuy
ShwyGuy

Reputation: 31

Compare dates in R if I only have the month and year

I am given a data frame where one of the column parameters is a year and month value (ex "2019-05"). I need to only display rows where the date value is later than a certain value. For instance, if I only wanted to show data later than a given year-month "2018-11".

Upvotes: 0

Views: 1166

Answers (1)

IceCreamToucan
IceCreamToucan

Reputation: 28705

You can convert them to dates, but in R < and > work on characters too, so you could just do something like this (assuming there's a leading 0 in the months with only 1 digit)

examp <- c('2011-01', '2013-08', '2018-04', '2018-12', '2019-05')

examp[examp > '2018-11']
#[1] "2018-12" "2019-05"

If you want to convert to dates, add a day to the end and use as.Date

examp <- as.Date(paste0(examp, '-01'))
examp
# [1] "2011-01-01" "2013-08-01" "2018-04-01" "2018-12-01" "2019-05-01"

examp[examp > as.Date('2018-11-01')]
# [1] "2018-12-01" "2019-05-01"

Upvotes: 1

Related Questions