计算数据框中日期的两列之间的天数 [英] calculating number of days between 2 columns of dates in data frame

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

问题描述

我有一个数据框,其中包含两列日期,格式为yyyy/mm/dd.我正在尝试为数据框内的每个观测值计算这两个日期之间的天数(并创建一个具有该天数的新变量).

I have a data frame which has two columns of dates in the format yyyy/mm/dd. I am trying to calculate the number of days between these two dates for each observation within the data frame (and create a new variable with this number of days in it).

到目前为止,我已经尝试使用此处给出的答案:

So far I have tried using the answer given here:

计算的两个日期之间的工作日数R

但要编辑代码,以便它计算总天数,而不只是工作日数.这只是出现错误说:

but editing the code so that it calculates number of total days rather than just the number of week days. This just came up with error saying:

Error in del/by : non-numeric argument to binary operator
In addition: Warning message:
In Ops.factor(to, from) : - not meaningful for factors

我也尝试使用此代码:

finish <- as.Date(survey$date, format="%yyyy/%mm/%dd")
start <- as.Date(survey$tx_start, format="%yyyy/%mm/%dd")
date_diff<-as.data.frame(finish-start)

计划使用"cbind"或等同于组合数据框天"的内容到我的数据框调查"其中包含数据.

with the plan of using "cbind" or something equivalent to combine the data frame "days" to my data frame "survey" which has data in it.

尽管这不会给我带来任何错误,但完成"过程中的观察结果却不尽人意.和开始"对象都是"NA_real_",因此date_diff数据帧将所有观测值列为NA.

Although this does not give me any errors, the observations within the "finish" and "start" objects are all "NA_real_", and the date_diff data frame therefore has all the observations listed as NA.

如果有人可以向我指出正确的方向,那就太好了!我发现的所有其他问题似乎都不是处理变量中的日期,而是作为单独的日期,将这些技术应用于变量并不是对我有用.

If someone could point me in the right direction that would be great! All the other question I have found do not seem to be dealing with dates within variables but as individual dates, and applying those techniques to variables hasn`t been working for me.

推荐答案

没有看到您的数据(您可以使用 dput(head(survey))的输出显示给我们),这是一个在黑暗中拍摄:

Without your seeing your data (you can use the output of dput(head(survey)) to show us) this is a shot in the dark:

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

survey$date_diff <- as.Date(as.character(survey$date), format="%Y/%m/%d")-
                  as.Date(as.character(survey$tx_start), format="%Y/%m/%d")
survey
       date   tx_start date_diff
1 2012/07/26 2012/01/01  207 days
2 2012/07/25 2012/01/01  206 days

这篇关于计算数据框中日期的两列之间的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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