MFR MFR - 17 days ago 4
R Question

Comparing two dates with different formats

I need to compare two dates for the following dataset:

structure(list(date = c(20160919L, 20161108L, 20160217L), TagActivationDate = structure(c(24L,
42L, 9L), .Label = c("1/10/2016", "1/11/2016", "10/10/2016",
"10/11/2016", "11/08/2016", "11/10/2016", "11/11/2016", "12/10/2016",
"12/11/2016", "13/10/2016", "13/11/2016", "14/10/2016", "14/11/2016",
"15/10/2016", "16/10/2016", "17/10/2016", "18/10/2016", "19/08/2016",
"19/10/2016", "2/10/2016", "20/10/2016", "21/10/2016", "22/10/2016",
"23/09/2016", "23/10/2016", "24/09/2016", "24/10/2016", "25/09/2016",
"25/10/2016", "26/10/2016", "27/10/2016", "28/09/2016", "28/10/2016",
"29/09/2016", "29/10/2016", "3/10/2016", "30/09/2016", "30/10/2016",
"31/10/2016", "4/10/2016", "5/10/2016", "5/11/2016", "6/10/2016",
"6/11/2016", "7/11/2016", "8/10/2016", "8/11/2016", "9/10/2016",
"9/11/2016"), class = "factor")), .Names = c("date", "TagActivationDate"
), row.names = c(NA, 3L), class = "data.frame")


One of them is integer and another one is factor, I need to label them if they have more than two days difference:

mydata$filtcases <- mydata$date >= ( mydata$TagActivationDate - 2)


I tried to converting them to different formats but none of them were successful. Any tip is appreciated.

Answer

As @zx8754 mentioned, try getting both of them in the same format and then find the difference between them

abs(as.Date(as.character(df$date), "%Y%m%d") - 
                as.Date(as.character(df$TagActivationDate), "%d/%m/%Y")) > 2
#[1] TRUE TRUE TRUE