使用R包从日期和小时(整数)构建时间对象

7

我得到的数据是以日期形式提供的,包括日期(格式为“YYYY-MM-DD”,例如“2015-03-11”)和编号表示一天中的小时数(0-23)。

最方便的方法是什么来生成这种形式的时间对象?

"2015-03-11" and hour = 0 ->  "2015-03-11 00:00"
"2015-03-11" and hour = 1 ->  "2015-03-11 01:00"
"2015-03-11" and hour = 2 ->  "2015-03-11 02:00"

我可以使用Base的日期函数或者xts或timeDate中的一些内容。这应该很容易,但我相信有人能够快速掌握它。
编辑:数据提供了两列,一列是日期,一列是数字。

你是否有一个字符串,类似于 "2015-03-11" and hour = 0" 或者是另外两列,一列为日期,另一列为从0到23的数字值? - akrun
两列 - 一列日期,一列数字。 - Richi W
它按照您的建议运行,并且我添加了一个时区,因为数据来自不同的时区。数据是UTC,我是CET as.POSIXct(sprintf('%s %02d', '2015-03-11', 2), format='%Y-%m-%d %H',tz = "UTC")。谢谢! - Richi W
当你说“时间对象”作为输出时,你想要 POSIXct 还是字符串? - smci
不重要 - 当我有了字符串,我就可以转换。谢谢! - Richi W
4个回答

5
你不需要使用外部包来完成这个任务。
如果你的数据格式如下:
df=data.frame(date=c("2015-03-11","2015-03-11","2015-03-11"),hour=0:2)

只需应用以下函数:
format(as.POSIXct(df$date)+df$hour*60*60, format = "%Y-%m-%d %H:%M")

4

假设我们有以下输入:

date <- c("2015-03-11", "2015-03-12")
hour <- 2:3

如果您遇到这种情况,请尝试以下解决方法之一: 1)chron
library(chron)
as.chron(date) + hour/24

提供:

[1] (03/11/15 02:00:00) (03/12/15 03:00:00)

2) POSIXct. 这个函数只使用R的基础功能,不需要安装任何软件包:

as.POSIXct(date) + 3600 * hour    

在我的系统上,给予:
[1] "2015-03-11 02:00:00 EDT" "2015-03-12 03:00:00 EDT"

如果您希望结果以UTC时区显示,请使用以下方法:

as.POSIXct(date, tz = "UTC") + 3600 * hour  

3) lubridate

library(lubridate)
ymd(date) + hours(hour)

提供:

[1] "2015-03-11 02:00:00 UTC" "2015-03-12 03:00:00 UTC"

如果你想使用当前时区,则需执行以下操作:

ymd(date, tz = "") + hours(hour)

请注意,chron解决方案提供了一个日期/时间类,不使用时区,从而消除了时区可能引起的许多问题。POSIXct和lubridate解决方案给出了特定时区的日期/时间,如所示。

3

您可以尝试

dtime <- with(df, as.POSIXct(sprintf('%s %02d', date, hour),
                    format = "%Y-%m-%d %H")) 

然后像其他帖子中一样使用format

或者

 library(lubridate)
 ymd_h(with(df, sprintf('%s %02d', date, hour)))

或稍微紧凑一些
ymd_h(do.call(paste, df))

1
@DavidArenburg,为此,我必须偷你的do.call :-) - akrun

2

试试这个。如果您希望,可以使用format在之后将其格式化为不带秒的形式,但我认为最好保留POSIXct类,以便您之后可以对其进行操作(添加或删除天数、秒数等)。

as.POSIXct(do.call(paste, df), format = "%Y-%m-%d %H")
## [1] "2015-03-11 00:00:00 IST" "2015-03-11 01:00:00 IST" "2015-03-11 02:00:00 IST"

不过,如果你坚持要得到精确的输出,这里有一个使用format函数的解决方案。

format(as.POSIXct(do.call(paste, df), format = "%Y-%m-%d %H"), "%Y-%m-%d %H:%M")
## [1] "2015-03-11 00:00" "2015-03-11 01:00" "2015-03-11 02:00"

数据

df <- structure(list(V1 = structure(c(1L, 1L, 1L), .Label = "2015-03-11", class = "factor"), 
    V2 = 0:2), .Names = c("V1", "V2"), class = "data.frame", row.names = c(NA, 
-3L))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接