在R中将数字转换为日期时间

时间:2015-01-16 10:35:22

标签: r datetime merge

我有一个包含2列的数据框。我希望格式列hhmm为%H:%M但代码不起作用:

DF$hhmm <-as.POSIXct(strptime(DF$hhmm, "%H%M"))

我还想将2列合并为1列DateTime,如2002-07-08 22:00

YYYY-MM-DD  hhmm
2002-07-08  2200    
2002-07-08  2300    
2002-07-09  0   
2002-07-09  100 
2002-07-09  200 
2002-07-09  300 
2002-07-09  400

1 个答案:

答案 0 :(得分:1)

您可以先使用sprintf()将列放在一起,然后使用as.POSIXct()

x <- with(df, sprintf("%s %04d", YYYY.MM.DD, hhmm))
data.frame(DateTime = as.POSIXct(x, format = "%Y-%m-%d %H%M"))
#              DateTime
# 1 2002-07-08 22:00:00
# 2 2002-07-08 23:00:00
# 3 2002-07-09 00:00:00
# 4 2002-07-09 01:00:00
# 5 2002-07-09 02:00:00
# 6 2002-07-09 03:00:00
# 7 2002-07-09 04:00:00

其中df

df <- structure(list(YYYY.MM.DD = structure(c(1L, 1L, 2L, 2L, 2L, 2L, 
2L), .Label = c("2002-07-08", "2002-07-09"), class = "factor"), 
hhmm = c(2200L, 2300L, 0L, 100L, 200L, 300L, 400L)), .Names = c("YYYY.MM.DD", 
"hhmm"), class = "data.frame", row.names = c(NA, -7L))