计算特定日期以来的天数

时间:2016-07-09 20:18:57

标签: r dataframe lubridate

我有一个数据框,其中包含日期,其中观察范围从1974-10-01到2014-30-09。我想在数据框中创建一个新列(" Day"),它指定自第一个时间段(即1974-10-01)以来的天数。

我已经拥有了代码,并且它非常适用于非常相似的数据帧,但我不知道为什么第二个数据帧不起作用。

1)代码如下:

library(lubridate)
ref_date <- dmy("01-10-1974")
df$Day <- as.numeric(difftime(df$Date, ref_date))

2)我的数据框的第一行是:

     Code  Area        Date    Height
1    2001  551.4 1975-04-01   120.209
2    2001  551.4 1976-01-06   158.699
3    2001  551.4 1977-01-21   128.289
4    2001  551.4 1978-02-23   198.254
5    2001  551.4 1979-07-31   131.811
[....]

3)我用代码(1)获得的内容如下:

     Code   Area       Date        Day    Height
1    2001  551.4 1975-04-01   15724800  120.209
2    2001  551.4 1976-01-06   39916800  158.699
3    2001  551.4 1977-01-21   72835200  128.289
4    2001  551.4 1978-02-23  107222400  198.254
5    2001  551.4 1979-07-31  152409600  131.811
[....]

我花了两个多小时想知道为什么没有任何线索。

有什么建议吗?

3 个答案:

答案 0 :(得分:1)

另一个选择

difftime(ref_date,df$Date,units = "days")

答案 1 :(得分:0)

您是否正在寻找以下示例:

df <- data.frame(Date = c("1975-04-01"))
> df
        Date
1 1975-04-01

df$new_col <- as.Date(as.character(df$Date), format="%Y-%m-%d") - as.Date(as.character("1974-10-01"), format="%Y-%m-%d")
> df
        Date  new_col
1 1975-04-01 182 days
> 

答案 2 :(得分:0)

只要日期是字符列,您的代码就会起作用。

library(lubridate)
ref_date <- dmy("01-10-1974")

df<- data.frame(Code=2001, Area=551.4,  Date=c("1975-04-01","1976-01-06","1977-01-21","1978-02-23","1979-07-31"), Height=c(120.209, 158.699, 128.289, 198.254, 131.811))

df$Day <- as.numeric(difftime(df$Date, ref_date))