# 从R中提取POSIXct中的小时和秒作为绘图目的

` ` start.time duration 1 2012-02-06 15:47:00 1 2 2012-02-06 15:02:00 2 3 2012-02-22 10:08:00 3 4 2012-02-22 09:32:00 4 5 2012-03-21 13:47:00 5` `

`class(foo\$start.time)`返回

` `[1] "POSIXct" "POSIXt"` `

` `foo <- data.frame(start.time = c("2012-02-06 15:47:00", "2012-02-06 15:02:00", "2012-02-22 10:08:00"), duration = c(1,2,3))` `

` `# using base::strptime t.str <- strptime(foo\$start.time, "%Y-%m-%d %H:%M:%S") # using lubridate::ymd_hms library(lubridate) t.lub <- ymd_hms(foo\$start.time)` `

` `# using base::format h.str <- as.numeric(format(t.str, "%H")) + as.numeric(format(t.str, "%M"))/60 # using lubridate::hour and lubridate::minute h.lub <- hour(t.lub) + minute(t.lub)/60` `

certificate这些方法是平等的：

` `identical(h.str, h.lub)` `

` `foo\$hr <- h.str # If you prefer, the choice can be made at random: foo\$hr <- if(runif(1) > 0.5){ h.str } else { h.lub }` `

` `library(ggplot2) qplot(foo\$hr, foo\$duration) +     scale_x_datetime(labels = "%S:00")` `

` `# Using R 2.14.2 # The same toy data foo <- data.frame(start.time = c("2012-02-06 15:47:00", "2012-02-06 15:02:00", "2012-02-22 10:08:00"), duration = c(1,2,3))` `

` `# Extract hour and minute as a character vector, of the form "%H:%M" substr(foo\$start.time, 12, 16)` `

` `# Store time information as POSIXct, using an arbitrary date foo\$time <- as.POSIXct(paste("2012-01-01", substr(foo\$start.time, 12, 16)))` `

` `# Plot it using base graphics plot(duration~time, data=foo) # Plot it using ggplot2 (0.9.2.1) library(ggplot2) qplot(x=time, y=duration, data=foo)` `

` `time <- c("1979-11-13T08:37:19-0500", "2014-05-13T08:37:19-0400"); time.posix <- as.POSIXct(time, format = "%Y-%m-%dT%H:%M:%S%z"); time.epoch <- as.vector(unclass(time.posix)); time.poslt <- as.POSIXlt(time.posix, tz = "America/New_York"); time.hour.new.york <- time.poslt\$hour + time.poslt\$min/60 + time.poslt\$sec/3600; > time; [1] "1979-11-13T08:37:19-0500" "2014-05-13T08:37:19-0400" > time.posix; [1] "1979-11-13 15:37:19 IST" "2014-05-13 15:37:19 IDT" > time.poslt; [1] "1979-11-13 08:37:19 EST" "2014-05-13 08:37:19 EDT" > time.epoch; [1] 311348239 1399984639 > time.hour.new.york; [1] 8.621944 8.621944` `