【发布时间】:2018-03-03 16:22:18
【问题描述】:
我有一列日期格式如下:
2013-05-25 14:10:00.00
...但我想把它放在这种格式
25/05/2013 14:10
...所以r 可以阅读它。
另外,我希望能够计算两列之间的时间。
我该怎么做?
【问题讨论】:
我有一列日期格式如下:
2013-05-25 14:10:00.00
...但我想把它放在这种格式
25/05/2013 14:10
...所以r 可以阅读它。
另外,我希望能够计算两列之间的时间。
我该怎么做?
【问题讨论】:
如果您将时间列作为POSIXt 或POSIXct 类的对象,只需使用函数format,如果不先转换列。
x <- as.POSIXct("2013-05-25 14:10:00.00", format = "%Y-%m-%d %H:%M:%OS")
y <- format(x, "%d/%m/%Y %H:%M")
y
#[1] "25/05/2013 14:10"
对于两次之间的差,可以使用diftime或更简单的减法运算符。
z <- Sys.time()
difftime(z, x)
#Time difference of 1743.164 days
z - x
#Time difference of 1743.164 days
difftime(z, x, units = "secs")
#Time difference of 150609340 secs
【讨论】:
为什么要在导入r之前先转换一下?
以你为例:
> library("lubridate")
> d <- "2013-05-25 14:10:00.00"
> d
[1] "2013-05-25 14:10:00.00"
我只是将它作为 R 中的字符类型放入变量中。但是,as_datetime() 将格式理解为日期和时间没有问题:
> as_datetime(d)
[1] "2013-05-25 14:10:00 UTC"
如果 R 认为数据是您读取数据时的一个因素,您可以先尝试将其转换为字符。
> d <- as.factor("2013-05-25 14:10:00.00")
> d
[1] 2013-05-25 14:10:00.00
Levels: 2013-05-25 14:10:00.00
as_datetime 以防万一似乎理解因子格式,但如果先转换为字符,它也能理解它。
> as_datetime(d)
[1] "2013-05-25 14:10:00 UTC"
> as_datetime(as.character(d))
[1] "2013-05-25 14:10:00 UTC"
【讨论】:
as_datetime
library 电话,以便人们知道您在做什么。