首页 > 解决方案 > 在 R 中将格式从数字更改为 POSIXct 对象

问题描述

我有一列包含这些日期和时间:

20121029 0,
20121029 100,
20121029 200,
20121029 300,
20121029 400 ...

它们的格式是“int”

我的任务是更改它们并以 POSIXct 格式创建一个表示时间和日期的列。

标签: rposixct

解决方案


这不是最优雅的解决方案,但它有效

library(stringr)
library(dplyr)

example_data <- c("20121029 0", "20121029 100", "20121029 2100")

# Extract the times
times <- example_data %>% strsplit(. , " ") %>% sapply(. , "[", 2)
times <- str_pad(times, max(nchar(times)), side="right", pad="0")

# Extract just the dates
dates <- example_data %>% substr(., 1, 8)

# Combine date and time and convert to POSIXct
date_time <- paste(dates, times) %>% as.POSIXct(., format="%Y%m%d %H%M")

推荐阅读