计算自特定日期以来的天数 [英] Count number of days since a specific date

查看:179
本文介绍了计算自特定日期以来的天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have got a dataframe with a column Date in which the observations range from 1974-10-01 to 2014-30-09. I would like to create a new column ("Day") in the dataframe which specify the number of day since the first time period day (i.e. 1974-10-01).

我已经有了代码,并且可以在非常相似的数据帧中完美运行,但是我不知道为什么在第二个数据帧中它不起作用.

I already have the code and it worked perfectly for a really similar dataframe but I do not know why with this 2nd dataframe it does not work.

1)代码如下:

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

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

2) The first rows of my dataframe are:

     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)获得的内容如下:

3) What I obtain with my code (1) is the following:

     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
[....]

我花了两个多小时来思考为什么没有任何线索.

I spent more than 2 hours wondering why without any clue.

有什么建议吗?

推荐答案

您是否正在寻找类似以下示例的内容:

Are you looking for something like the example below :

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
> 

这篇关于计算自特定日期以来的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆