计算时间戳之间的差异

时间:2017-12-11 18:39:41

标签: r

我试着找出两个时间戳之间的区别。 codeQ:

survey <- data.frame(date=c("07/2012","07/2012"),tx_start=c("01/2012","01/2012"))
survey$date_diff <- as.Date(as.character(survey$date), format="%m/%Y")-
    as.Date(as.character(survey$tx_start), format="%m/%Y")
survey

我希望在新专栏中有所不同但我拿NA

结果:

> survey
     date tx_start date_diff
1 07/2012  01/2012   NA days
2 07/2012  01/2012   NA days

我应该更改as.Date几个月或几年?

根据Gregor的评论更新:

    > survey <- data.frame(date=c("07/2012","07/2012"),tx_start=c("01/2012","01/2012"))
> survey$date <- as.Date(paste0("01/", as.character(survey$date)), "%d/%m/%Y")
> survey$tx_start <- as.Date(paste0("01/", as.character(survey$tx_start)), "%d/%m/%Y")
> survey$date_diff <- as.Date(survey$date, format="%d/%m/%Y")-
+     as.Date(survey$tx_start, format="%d/%m/%Y")
> survey
        date   tx_start date_diff
1 2012-07-01 2012-01-01  182 days
2 2012-07-01 2012-01-01  182 days

1 个答案:

答案 0 :(得分:1)

我通常会将日期转换为POSIXct格式。然后,当使用正常语法进行直接差异时,您将以秒为单位得到答案。基础R中还有一个difftime()函数,您也可以使用它:

survey <- data.frame(date=c("07/2012","07/2012"),tx_start=c("01/2012","01/2012"))

# Dates are finicky, add a day so that conversion will work
survey$date2 <- paste0("01/",survey$date)
survey$tx_start2 <- paste0("01/",survey$tx_start)

# conversion
survey$date2 <-  as.POSIXct(x=survey$date2,format="%d/%m/%Y")
survey$tx_start2 <-  as.POSIXct(x=survey$tx_start2,format="%d/%m/%Y")

# take the difference
survey$date_diff <- with(survey,difftime(time1=date2,time2=tx_start2,units="hours"))