将矩阵中的所有单元格转换为R中的时间格式

时间:2016-01-14 02:00:58

标签: r datetime matrix

我有一个像字符格式一样的大矩阵

a <- as.matrix(c("18:12:30", "6:15:30", "12:31:40"))
b <- as.matrix(c("1:50:30", "9:50:32", "5:30:43"))
c <- as.matrix(c("7:54:23", "22:45:34", "12:54:23"))
mat <- cbind(a,b,c)

我想将每个值转换为时间格式。我知道我可以使用

逐行完成
a <- strptime(a, "%H:%M:%OS")
b <- strptime(b, "%H:%M:%OS")
c <- strptime(b, "%H:%M:%OS")

但我有一个大矩阵,所以即使我有更多的列和行,我也在寻找能够做到这一点的函数。

1 个答案:

答案 0 :(得分:1)

请注意您的时间和日期数据的存储方式。 strptime转换为POSIXlt,其中始终包含日期,因此如果您未指定日期,strptime会插入今天的日期。这可能会产生巨大的再现性问题。

相反,您需要使用包来获得合适的时间数据结构。 chron有一个很简单的问题。要重新创建data.frame次(矩阵只能存储数字):

library(chron)

# lapply chron over the columns of your data; collect in data.frame
time_mat <- do.call(data.frame, lapply(list(a, b, c), function(x){chron(times. = x)}))

# make the names prettier
names(time_mat) <- c('a', 'b', 'c')

给你

> time_mat
         a        b        c
1 18:12:30 01:50:30 07:54:23
2 06:15:30 09:50:32 22:45:34
3 12:31:40 05:30:43 12:54:23

times,在任何用法中都会保持一致。