将dataframe中的数字列转换为R中的时间格式

将dataframe中的数字列转换为R中的时间格式,r,type-conversion,R,Type Conversion,我有一个包含2列的数据框,包括小时和分钟。我想将这些列转换为时间格式。数据如下所示: dep_time sched-dep-time 413 300 516 833 2344 1700 644 2230 1233 1800 我想得到: dep_time sched-dep-time 04:13 03:00 05:16 08:33 23:44 17:00 06:44

我有一个包含2列的数据框,包括小时和分钟。我想将这些列转换为时间格式。数据如下所示:

dep_time    sched-dep-time
413         300
516         833
2344        1700
644         2230
1233        1800
我想得到:

dep_time    sched-dep-time
04:13       03:00
05:16       08:33
23:44       17:00
06:44       22:30
12:33       18:00
这里有一个解决方案:

time <- data.frame(c('413','516','2344','644','1233'), c('300','833','1700','2230','1800'))
colnames(time) <- c("dep_time", "sched-dep-time")

x1 <- as.vector(time[,1])
x2 <- as.vector(time[,2])

mins  <-  substr(x1, nchar(x1)-1, nchar(x1))
hour  <-  substr(x1, 0, nchar(x1)-2)
time[,1]  <-  paste0(hour, ':', mins)

mins  <-  substr(x2, nchar(x2)-1, nchar(x2))
hour  <-  substr(x2, 0, nchar(x2)-2)
time[,2]  <-  paste0(hour, ':', mins)

现在,我发布一个答案,直到我找到正确的答案:

as.data.frame(sapply( x, function(y)  
                         substr(as.POSIXct(sprintf("%04.0f", y), format='%H%M'), 12, 16)))

# dep_time sched.dep.time
# 1    04:13          03:00
# 2    05:16          08:33
# 3    23:44          17:00
# 4    06:44          22:30
# 5    12:33          18:00
数据:


x现在您以我写下的数字为例。该列有大约300000个数据,我需要记录所有这些时间吗?因为我无法访问您的数据集,所以我必须创建自己的数据集。指定数据集时间或更改数据集的命名时间已在中得到答复
as.data.frame(sapply( x, function(y)  
                         substr(as.POSIXct(sprintf("%04.0f", y), format='%H%M'), 12, 16)))

# dep_time sched.dep.time
# 1    04:13          03:00
# 2    05:16          08:33
# 3    23:44          17:00
# 4    06:44          22:30
# 5    12:33          18:00
x <- read.table(text="dep_time    sched-dep-time
413         300
516         833
2344        1700
644         2230
1233        1800", header=T)