【问题标题】:R: Date Operation Results in Empty DatesR:日期运算结果为空日期
【发布时间】:2021-07-28 02:48:00
【问题描述】:

我正在使用 R 编程语言。我正在尝试区分两个日期列。两个日期的格式如下:2010-01-01 12:01

当我将文件带入 R 时,日期为“因子”格式。这是我在 R 中重新创建文件的尝试:

#how my file looks like when I import it into R

date_1 = c("2010-01-01 13:01 ", "2010-01-01 14:01" )
date_2 = c("2010-01-01 15:01 ", "2010-01-01 16:01" )

file = data.frame(date_1, date_2)
file$date_1 = as.factor(file$date_1)
file$date_2 = as.factor(file$date_2)

现在,我正在尝试创建一个新列,用于计算这些日期之间的差异(以分钟为单位)

我首先尝试将两个日期变量转换为适当的“日期”格式:

#convert to date formats:
    
  file$date_a = as.POSIXlt(file$date_1,format="%Y-%m-%dT%H:%M")
  file$date_b = as.POSIXlt(file$date_2,format="%Y-%m-%dT%H:%M")

然后,我试着拿差价:

file$diff = difftime(file$date_a, file$date_b, units="mins")

但这会导致“NA's”:

> file

             date_1            date_2 date_a date_b    diff
1 2010-01-01 13:01  2010-01-01 13:01    <NA>   <NA> NA mins
2  2010-01-01 13:01  2010-01-01 13:01   <NA>   <NA> NA mins

谁能告诉我我做错了什么?

谢谢

参考:How to get difference (in minutes) between two date strings?

【问题讨论】:

  • 我没有转换成因子。当我将我的文件从 excel 上传到 R 时,日期已经是“因素”格式。我试图复制我正在使用的条件

标签: r date data-manipulation datediff


【解决方案1】:

字符串中没有T。所以,我们需要格式为

difftime(as.POSIXct(file$date_1, format = '%Y-%m-%d %H:%M'),
       as.POSIXct(file$date_2, format = '%Y-%m-%d %H:%M'), units = 'mins')
#Time differences in mins
#[1] -120 -120

【讨论】:

  • 感谢您的回答!我尝试了这段代码并得到了以下结果:时间差 in mins [1] 0 0 ...我认为它不应该是 0?
  • @Noob 在创建的数据中两者是相同的。因此,我不确定应该如何将其评估为不同。当您从 excel 读取数据时(不确定您使用的是哪个包),可以选择指定列类型。如果有秒和毫秒,可能是不同的
  • 对不起,我把它们改成了不同的时间,它们仍然返回为 0
  • @Noob 抱歉,即使使用因子类,我也无法用你的新示例复制它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-25
  • 1970-01-01
  • 1970-01-01
  • 2011-10-07
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
相关资源
最近更新 更多