转换为POSIXct时的维护结构

问题描述 投票:1回答:1

我正在尝试将两列unix时间转换为实际日期时间。请参见下面的示例:

df = as.matrix(data.frame(col1 = as.numeric(sample(1316006155:1316009155,10)), col2 = as.numeric(sample(1316006155:1316009155,10))))

as.POSIXct(df,origin = "1970-01-01",tz = "GMT")

尽管以上工作有效,但我松散了数据的结构(即创建了一个大向量)。如何维护结构(即分别转换为POSIXct的两列)。另外,我认为如果我在数据帧中有unix时间,我可以使用以下应用代码来逐行更改(尽管我知道从上面进行矢量化处理的速度更快),但这是行不通的。为什么?

apply(df,2,function(x) as.POSIXct(x,origin = "1970-01-01",tz = "GMT"))

谢谢

r vectorization apply posixct
1个回答
0
投票
您正在使用matrix es,但是在"date"中不能将"POSIXct"类作为matrix。特别是apply作为结果得出矩阵,因此将“新”结果再次强制为数字。原因是matrix()使用实际上具有as.vector自变量的mode=,而不是"date", "POSIXct", ...

所以您可以

任一强制转换为"character"格式:

res1 <- apply(df, 2, function(x) as.character(as.POSIXct(x,origin="1970-01-01", tz="GMT")))
或更有效地:

res1 <- array(as.character(as.POSIXct(df, origin="1970-01-01", tz="GMT")), dim=dim(df), dimnames=dimnames(df)) # col1 col2 # [1,] "2011-09-14 13:59:23" "2011-09-14 13:21:50" # [2,] "2011-09-14 13:55:23" "2011-09-14 13:42:59" # [3,] "2011-09-14 13:35:31" "2011-09-14 13:18:39" # [4,] "2011-09-14 13:34:12" "2011-09-14 14:00:24" # [5,] "2011-09-14 13:36:46" "2011-09-14 13:56:52" # [6,] "2011-09-14 13:26:28" "2011-09-14 13:47:37" # [7,] "2011-09-14 13:50:51" "2011-09-14 13:30:53" # [8,] "2011-09-14 13:35:06" "2011-09-14 13:25:55" # [9,] "2011-09-14 13:38:01" "2011-09-14 13:37:41" # [10,] "2011-09-14 13:50:26" "2011-09-14 13:31:26" str(res1) # chr [1:10, 1:2] "2011-09-14 13:59:23" "2011-09-14 13:55:23" ... # - attr(*, "dimnames")=List of 2 # ..$ : NULL # ..$ : chr [1:2] "col1" "col2"

或,

将矩阵强制转换为"data.frame",使您可以使用lapplyres2 <- as.data.frame(lapply(as.data.frame(df), function(x) as.POSIXct(x, origin="1970-01-01", tz="GMT"))) # col1 col2 # 1 2011-09-14 13:59:23 2011-09-14 13:21:50 # 2 2011-09-14 13:55:23 2011-09-14 13:42:59 # 3 2011-09-14 13:35:31 2011-09-14 13:18:39 # 4 2011-09-14 13:34:12 2011-09-14 14:00:24 # 5 2011-09-14 13:36:46 2011-09-14 13:56:52 # 6 2011-09-14 13:26:28 2011-09-14 13:47:37 # 7 2011-09-14 13:50:51 2011-09-14 13:30:53 # 8 2011-09-14 13:35:06 2011-09-14 13:25:55 # 9 2011-09-14 13:38:01 2011-09-14 13:37:41 # 10 2011-09-14 13:50:26 2011-09-14 13:31:26 str(res2) # 'data.frame': 10 obs. of 2 variables: # $ col1: POSIXct, format: "2011-09-14 13:59:23" "2011-09-14 13:55:23" ... # $ col2: POSIXct, format: "2011-09-14 13:21:50" "2011-09-14 13:42:59" ...

数据:

df <- structure(c(1316008763, 1316008523, 1316007331, 1316007252, 1316007406, 1316006788, 1316008251, 1316007306, 1316007481, 1316008226, 1316006510, 1316007779, 1316006319, 1316008824, 1316008612, 1316008057, 1316007053, 1316006755, 1316007461, 1316007086), .Dim = c(10L, 2L), .Dimnames = list( NULL, c("col1", "col2")))
© www.soinside.com 2019 - 2024. All rights reserved.