2016-11-23 95 views
2

我需要比較兩個日期以下數據集比較兩個日期:不同格式

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") 

其中一個是整數,另外一個因素,我需要標記他們,如果他們有超過兩天差異:

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

我試圖將它們轉換爲不同的格式,但都沒有成功。任何提示表示讚賞。

+0

所以預期輸出是'爲TRUE'他們全部? –

+0

在這個例子中是 – MFR

+0

將兩者轉換爲相同的日期格式,然後得到不同。 – zx8754

回答

2

正如@ zx8754提到,嘗試以相同的格式讓他們兩個,然後發現他們

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

之間的區別使用lubridate:

library(lubridate) 

mydata$filtcases <- abs(ymd(mydata$date) - dmy(mydata$TagActivationDate)) > 2