Re: [问题] 日期转换格式

楼主: celestialgod (天)   2019-08-30 19:28:11
※ 引述《jerkoffme (摩德男孩)》之铭言:
: [问题类型]:
: 资料格式转换
: [软件熟悉度]:
: 使用者(已经有用R 做过不少作品)
: [问题叙述]:
: 想将 data.table 格式的 table 叫 pop 并将其中一个变量转换为时间变量,
: 该变量为 char 的格式,但使用日期转化的函数后最后都会变成数字
: [程式范例]:
: 例如
: post_time
: 2019/8/28 16:43
: 2019/8/28 15:48
: 但我用
: tdf5 <- sapply(pop$post_time, as.POSIXct, format = "%Y/%m/%d %H:%M")
: View(tdf5)
: 结果就会变成
: 1566981780
: 1566978480
: 请问为何会这样
先回答问题,sapply的simplify造成的
可以看一下source code:
answer <- lapply(X = X, FUN = FUN, ...)
if (!isFALSE(simplify) && length(answer))
simplify2array(answer, higher = (simplify == "array"))
simplify2array(x, higher = TRUE):
unlist(x, recursive = FALSE, use.names = FALSE)
可以看到sapply用了unlist去做simplify
然后unlist不认得POSIXt这个class (因为它丢进C里,只用最原本的型别: 整数)
而且它没有再转换回去,所以你最后sapply看到的就只剩下整数了
那怎么做?
两个方式:
1. 根本不需要用sapply,直接用as.POSIXct做就好:
as.POSIXct(DT$post_time)
2. 舍弃sapply改成用lapply + do.call + c取代
do.call(c, lapply(DT$post_time, as.POSIXct))
另外推文说的lubridate也可以,一样结果:
parse_date_time(DT$post_time, "ymdHM")

as_datetime(DT$post_time, format = "%Y/%m/%d %H:%M")
: [环境叙述]:
: R version 3.5.3 (2019-03-11)
: Platform: x86_64-w64-mingw32/x64 (64-bit)
: Running under: Windows >= 8 x64 (build 9200)
作者: bboybighead2 (脚毛会唱歌)   2019-09-01 13:41:00
推 很清楚
作者: jerkoffme (摩德男孩)   2019-09-13 02:31:00
感谢解惑

Links booklink

Contact Us: admin [ a t ] ucptt.com