首页 > 解决方案 > 想要将以下内容组合到 R 中的日期时间列中

问题描述

我有以下方式的列

日期、小时分钟列

第一列有年月日。我想将第 1、4、5 列合并为 R 中的 DateTime 格式。请帮助我。我已经使用 as.date 但出现错误。

标签: ras.date

解决方案


下面的函数将 3 列组合成一个 class 对象"POSIXct"

  1. 以 格式 结合年、月、日的列yyyymmdd
  2. 一个小时的专栏;
  3. 分钟专栏。

秒数设置为零。

toDateTime <- function(x){
  d <- as.Date(x[[1]], format = "%Y%m%d")
  ISOdatetime(format(d, "%Y"), format(d, "%m"), format(d, "%d"), 
              hour = x[[2]], min = x[[3]], sec = 0L)
}

toDateTime(df1[c(1, 4, 5)])
# [1] "2001-01-01 01:00:00 WET" "2001-01-01 01:30:00 WET"
# [3] "2001-01-01 02:00:00 WET" "2001-01-01 02:30:00 WET"
# [5] "2001-01-01 03:00:00 WET" "2001-01-01 03:30:00 WET"
# [7] "2001-01-01 04:00:00 WET" "2001-01-01 04:30:00 WET"
# [9] "2001-01-01 05:00:00 WET" "2001-01-01 05:30:00 WET"
#[11] "2001-01-01 06:00:00 WET" "2001-01-01 06:30:00 WET"
#[13] "2001-01-01 07:00:00 WET" "2001-01-01 07:30:00 WET"

测试数据

在接下来的测试数据中,我将列和 3 设置为NA,因为它们没有被使用。

dates <- "20010101"
hour <- rep(1:7, each = 2)
min <- rep(c(0, 30), length.out = 14)
df1 <- data.frame(dates, times = NA, d = NA, hour, min)

推荐阅读