理解 R 中的日期/时间(POSIXc 和 POSIXct)
我正在读取一个表,它包含描述时间戳的字符串。我只想从字符串转换为内置日期时间类型...
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")
如果我尝试将日期时间列存储到 data.frame 中,我会得到一个奇怪的错误:
R> Q$ts <- ts
Error in `$<-.data.frame`(`*tmp*`, "ts", value = list(sec = c(0, 0, 0, :
replacement has 9 rows, data has 5
但是如果我遍历数据中保存的数字表示形式。框架,它有效......
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
对理解情况有帮助吗?
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 `lt;-.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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
strptime
返回类POSIXlt
,数据框中需要POSIXct
:类
POSIXct
表示自开始以来的秒数1970 作为数值向量。 POSIXlt 类是表示秒、分、小时、日、月、年等的向量命名列表。
strptime
returns classPOSIXlt
, you needPOSIXct
in the data frame:Class
POSIXct
represents the (signed) number of seconds since the beginning of1970 as a numeric vector. Class
POSIXlt
is a named list of vectors representing sec, min, hour, mday, mon, year, etc.