所以我有一组这样的时间戳:
datetime<-c("2011-09-28 03:33:00", "2011-08-24 13:41:00", "2011-09-19 16:14:00", "2011-08-18 11:01:00", "2011-09-17 06:35:00", "2011-08-15 12:48:00")
我想制作一个只有时间的直方图。我所做的是在空格处拆分列以仅获取时间,然后转换回POSIXct对象以便qplot绘制它:
library(ggplot2, stringr)
qplot(as.POSIXct(strptime((str_split_fixed(as.character(time), " ", 2)[,2]), "%H:%M:%S")))
但是,as.POSIXct(strptime((str_split_fixed(as.character(datetime), " ", 2)[,2]), "%H:%M:%S"))
的输出是
"2011-10-04 03:33:00 PDT" "2011-10-04 13:41:00 PDT" "2011-10-04 16:14:00 PDT" "2011-10-04 11:01:00 PDT" "2011-10-04 06:35:00 PDT" "2011-10-04 12:48:00 PDT"
qplot描绘了我想要的东西,但这对我来说似乎是一个令人费解的黑客。当然有更好的方法来做到这一点?我可以转换成纪元时间并绘制那个,但我试图避免这样做是一个额外的步骤。
更大的问题是,“我如何控制strptime的输出?”
答案 0 :(得分:15)
这种做法怎么样?
require("ggplot2")
dtstring <- c(
"2011-09-28 03:33:00", "2011-08-24 13:41:00", "2011-09-19 16:14:00",
"2011-08-18 11:01:00", "2011-09-17 06:35:00", "2011-08-15 12:48:00"
)
dtPOSIXct <- as.POSIXct(dtstring)
# extract time of 'date+time' (POSIXct) in hours as numeric
dtTime <- as.numeric(dtPOSIXct - trunc(dtPOSIXct, "days"))
p <- qplot(dtTime) + xlab("Time slot") + scale_x_datetime(format = "%S:00")
print(p)
计算dtPOSIXct - trunc(dtPOSIXct, "days")
以小时为单位提取POSIXct类对象的时间。
ggplot2-0.9.1
:
require("ggplot2")
require("scales")
dtstring <- c(
"2011-09-28 03:33:00", "2011-08-24 13:41:00", "2011-09-19 16:14:00",
"2011-08-18 11:01:00", "2011-09-17 06:35:00", "2011-08-15 12:48:00"
)
dtPOSIXct <- as.POSIXct(dtstring)
# extract time of 'date+time' (POSIXct) in hours as numeric
dtTime <- as.numeric(dtPOSIXct - trunc(dtPOSIXct, "days"))
p <- qplot(dtTime) + xlab("Time slot") +
scale_x_datetime(labels = date_format("%S:00"))
print(p)
ggplot2-0.9.3.1
:
require("ggplot2")
require("scales")
dtstring <- c(
"2011-09-28 03:33:00", "2011-08-24 13:41:00", "2011-09-19 16:14:00",
"2011-08-18 11:01:00", "2011-09-17 06:35:00", "2011-08-15 12:48:00"
)
dtPOSIXct <- as.POSIXct(dtstring)
# extract time of 'date+time' (POSIXct) in hours as numeric
dtTime <- as.numeric(dtPOSIXct - trunc(dtPOSIXct, "days"))
class(dtTime) <- "POSIXct"
p <- qplot(dtTime) + xlab("Time slot") +
scale_x_datetime(labels = date_format("%S:00"))
print(p)
答案 1 :(得分:4)
只需使用基本工具:
dtstring <- c("2011-09-28 03:33:00", "2011-08-24 13:41:00", "2011-09-19 16:14:00", "2011-08-18 11:01:00", "2011-09-17 06:35:00", "2011-08-15 12:48:00")
datetime <- as.POSIXct(dtstring)
library(ggplot2)
qplot(datetime)
字符串的格式是使用as.POSIXct
进行解析的默认格式,有关详细信息,请参阅?strptime
,或者您是否拥有此格式以外的内容。
如果您想要日期时间值中的特定字符串格式,请使用format
,如
format(datetime, "%d-%b")
[1] "28-Sep" "24-Aug" "19-Sep" "18-Aug" "17-Sep" "15-Aug"
再次,请参阅?strptime
了解详情。如果您确实要删除时间值,可以使用Date
类。请注意,日期时间或日期需要完整的结构,任何其他表示只是格式化文本。
qplot(as.Date(日期时间))