理解R中的日期/时间(POSIXc和POSIXct) [英] understanding dates/times (POSIXc and POSIXct) in R
问题描述
R> Q< - read.table(textConnection('
tsstring
12009-09-30 10:00:00
22009-09-30 10:15:00
32009-09-30 10:35:00
42009-09-30 10:45:00
52009-09-30 11:00:00
),as.is = TRUE,header = TRUE)
R> ts< - strptime(Q $ tsstring,%Y-%m-%d%H:%M:%S,tz =UTC)
如果我尝试将datetime列存储到data.frame中,我会发现一个好奇的错误:
R> ($ * tmp *`,ts,value = list(sec = c(0,0,0,...
替换有9行,数据有5
但如果我经历了一个数字表示data.frame,它的工作原理...
R> EPOCH< - strptime(1970-01-01 00: 00:00,%Y-%m-%d%H:%M:%S,tz =UTC)
R> Q $ minutes< - as.numeric(difftime EPOCH,tz =UTC),units =mins)
R> Q $ ts
任何帮助了解情况?
strptime
返回类 POSIXlt
,数据框中需要 POSIXct
:
R> class(strptime(2009-09-30 10:00:00,%Y-%m-%d% H:%M:%S,tz =UTC))
[1]POSIXtPOSIXlt
R>类(as.POSIXct(2009-09-30 10:00 :00,%Y-%m-%d%H:%M:%S,tz =UTC))
[1]POSIXtPOSIXct
Class POSIXct
表示从
1970开始的(签名)秒数作为数字向量。类 POSIXlt
是代表秒,分,小时,日,月,年等的向量列表。
R>不带(strptime(2009-09-30 10:00:00,%Y-%m-%d%H:%M:%S,tz =UTC))
$ sec
[1] 0
$ min
[1] 0
$ hour
[1] 10
$ mday
[1] 30
$ mon
[1] 8
$ year
[1] 109
$ wday
[1] 3
$ yday
[1] 272
$ isdst
[1] 0
attr(,tzone)
[1]UTC
R&不分类(as.POSIXct(2009-09-30 10:00:00,%Y-%m-%d%H:%M:%S,tz =UTC))
[ 1] 1.254e + 09
attr(,tzone)
[1]UTC
I'm reading a table and it contains strings that describe timestamps. I just want to convert from string to a built-in datetime type...
R> Q <- read.table(textConnection('
tsstring
1 "2009-09-30 10:00:00"
2 "2009-09-30 10:15:00"
3 "2009-09-30 10:35:00"
4 "2009-09-30 10:45:00"
5 "2009-09-30 11:00:00"
'), as.is=TRUE, header=TRUE)
R> ts <- strptime(Q$tsstring, "%Y-%m-%d %H:%M:%S", tz="UTC")
if I try to store the datetime column into the data.frame, I get a curious error:
R> Q$ts <- ts
Error in `$<-.data.frame`(`*tmp*`, "ts", value = list(sec = c(0, 0, 0, :
replacement has 9 rows, data has 5
but if I go through a numeric representation held in the data.frame, it works...
R> EPOCH <- strptime("1970-01-01 00:00:00", "%Y-%m-%d %H:%M:%S", tz="UTC")
R> Q$minutes <- as.numeric(difftime(ts, EPOCH, tz="UTC"), units="mins")
R> Q$ts <- EPOCH + 60*Q$minutes
any help in understanding the situation?
strptime
returns class POSIXlt
, you need POSIXct
in the data frame:
R> class(strptime("2009-09-30 10:00:00", "%Y-%m-%d %H:%M:%S", tz="UTC"))
[1] "POSIXt" "POSIXlt"
R> class(as.POSIXct("2009-09-30 10:00:00", "%Y-%m-%d %H:%M:%S", tz="UTC"))
[1] "POSIXt" "POSIXct"
Class POSIXct
represents the (signed) number of seconds since the beginning of
1970 as a numeric vector. Class POSIXlt
is a named list of vectors representing sec, min, hour, mday, mon, year, etc.
R> unclass(strptime("2009-09-30 10:00:00", "%Y-%m-%d %H:%M:%S", tz="UTC"))
$sec
[1] 0
$min
[1] 0
$hour
[1] 10
$mday
[1] 30
$mon
[1] 8
$year
[1] 109
$wday
[1] 3
$yday
[1] 272
$isdst
[1] 0
attr(,"tzone")
[1] "UTC"
R> unclass(as.POSIXct("2009-09-30 10:00:00", "%Y-%m-%d %H:%M:%S", tz="UTC"))
[1] 1.254e+09
attr(,"tzone")
[1] "UTC"
这篇关于理解R中的日期/时间(POSIXc和POSIXct)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!