-1

I am trying to make a subset based on date conditions. I uploaded a dataset and tried to convert the date from POSIXct to a date class using this code:

as.Date(weatherDump$date, "%Y-%m-%d")

It seemed to convert the date to y/m/d but when I try and run the subset I get an error:

weather2013to2018 <- subset(weatherDump, date >= "2013-01-01" & date<= "2017-12-31")
Warning messages:
1: In Ops.factor(date, "2013-01-01") : ‘>’ not meaningful for factors
2: In Ops.factor(date, "2017-12-31") : ‘<’ not meaningful for factors

when I check the class(date) it is Function.

I presume I have gone wrong on the date conversion?

  • 1
    Can you provide a reproducible example of your dataset ? https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – dc37 Dec 15 '19 at 23:33

1 Answers1

2

First if you perform any operation on an object you need to assign it back, for changes to reflect.

weatherDump$date <- as.Date(weatherDump$date, "%Y-%m-%d")
#In this case you can only use as.Date
#weatherDump$date <- as.Date(weatherDump$date)

Second, if you want to check the class of a column you need to reference it with dataframe name (unless you have attached the dataframe which you should never do.)

class(weatherDump$date) 

Third and most important if you are comparing dates you need to make sure that the objects with which you are comparing are both of class dates as well (and not characters).

weather2013to2018 <- subset(weatherDump, date >= as.Date("2013-01-01") & 
                                         date<= as.Date("2017-12-31"))

An alternative is with lubridate which makes handling of dates easier.

library(lubridate)
weatherDump$date <- ymd(weatherDump$date)
weather2013to2018 <- subset(weatherDump, year(date) >= 2013 & year(date) <= 2017)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213