r - 想要将以下内容组合到 R 中的日期时间列中
解决方案
下面的函数将 3 列组合成一个 class 对象"POSIXct"
。
- 以 格式 结合年、月、日的列
yyyymmdd
; - 一个小时的专栏;
- 分钟专栏。
秒数设置为零。
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)
推荐阅读
- sql - 大学任务 - 返回为出版名为“xy”的书的出版商写书的所有作者的地址
- swift - Swift:如何从 Lightroom 中重现高光和阴影效果?
- asp.net - CSV Helper 第一行被跳过
- jquery - 使用带有 CSS 动画的 jQuery 滑入菜单(在 wordpress 主题中)
- javascript - 使用嵌套 div 切换 CSS 类
- rabbitmq - Rabbitmq集群,当节点下线时,如何保证下线队列接收到来自fanout exchange的消息?
- node.js - 开玩笑地自动替换导入
- python - 为什么 Kivy ScreenManager 在 Kivy 中无法识别我的屏幕?
- python - 重塑DataFrame,改变列的位置
- java - 如何检查字符串是否是速度代码