Suraj
Suraj

Reputation: 41

comparing the date in my excel file with system date

I have an excel file which has two columns start_date and end_date. I want to compare the end_date with the system date but everytime I use this code I get an error:

Incompatible methods ("ops.Date", "Ops.POSIXt") for "<"

I am reading excel file using

x<-read_excel("book.xlxs", Header="TRUE")

And now I am using

Myframe<-ifelse(x$end_date>Sys.Date())

What to do now?

Upvotes: 3

Views: 344

Answers (1)

Abdou
Abdou

Reputation: 13274

The error comes from the fact that you are trying to compare two objects of different classes. The call to Sys.Date returns an object of class Date. You can check that by calling class(Sys.Date). This returns Date. Moreover, it looks like you are using the readxl package, which usually imports datetime columns as POSIXct objects. As a result, you are trying to compare POSIXct objects with Date objects. This will almost always cause errors. As recommend in the comments, you should either convert Sys.Date to a POSIXct object with the function as.POSIXct or you can convert the values in the column end_date to Date objects. I recommend you do the first because you're only converting one value with the following line of code:

Myframe<-ifelse(x$end_date > as.POSIXct(Sys.Date()), 'TRUE_VAL', 'FALSE_VAL')

If no value in the end_date is greater than as.POSIXct(Sys.Date()), the comparison x$end_date > as.POSIXct(Sys.Date()) will return an empty vector. That's why you are seeing logical(0). This means that it is an R vector of logical values. But since it is empty, R will return logical(0).

If you changed the comparison to x$end_date <= as.POSIXct(Sys.Date()), you may see a vector of logical values (TRUE or FALSE).

Furthermore, if you're looking to have a new column that tracks which rows in the column end_date passed the comparison test, you can do the following:

x$end_date_passed <- ifelse(x$end_date > as.POSIXct(Sys.Date()), 'yes', 'no')

The new column here is called end_date_passed.

I hope this helps.

Upvotes: 1

Related Questions