R中的日期计算天数

时间:2017-07-09 12:59:32

标签: r

我的数据是

customer_id Last_city    First city       recent_date
1020         Jaipur       Gujarat         20130216
1021         Delhi        Lucknow         20130129
1022         Mumbai       Punjab          20130221

我希望找到最近日期和今天(每条记录)的天数。

1 个答案:

答案 0 :(得分:0)

difftime函数计算天,小时,分钟等的时差。 首先,需要将日期字符串解析为日期表示(例如DatePOSIXct),然后将其与当前日期/时间进行比较。

# create dummy data.frame for testing
df <- data.frame("customer_id"=1020, "Last_city"="Jaipur",
    "First_city"="Gujarat", "recent_date"="20130216",
    stringsAsFactors = FALSE)

now <- Sys.Date()
# parse date into date type (Note: %Y=4-digit year, %y=2-digit year)
df$date = as.Date(df$recent_date, format = "%Y%m%d") 
# next calculate the difference between recent date and current time
df$diff = as.double(difftime(now, df$date, units = c("days")))

> df
  customer_id Last_city First_city recent_date       date  diff
1        1020    Jaipur    Gujarat    20130216 2013-02-16  1604

如果想要在几周内获得差异

>  as.double(difftime(now, df$date, units = c("weeks")))
[1] 229.1429