问题描述
假设我有以下 data.frame
foo
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$duration
与 foo$start.time
的图.在我的场景中,我只对一天中的时间感兴趣,而不是一年中的实际日期.如何从 POSIXct
类向量中提取一天中的时间为 hours:seconds?
I'd like to create a plot of foo$duration
v. foo$start.time
. In my scenario, I'm only interested in the time of day rather than the actual day of the year. How does one go about extracting the time of day as hours:seconds from POSIXct
class of vector?
推荐答案
这是一个很好的问题,突出了在 R 中处理日期的一些困难.lubridate 包非常方便,所以下面我介绍两种方法,一种使用碱(如@RJ- 所建议的),另一种使用 lubridate.
This is a good question, and highlights some of the difficulty in dealing with dates in R. The lubridate package is very handy, so below I present two approaches, one using base (as suggested by @RJ-) and the other using lubridate.
重新创建原始帖子中的(前两行)数据框:
Recreate the (first two rows of) the dataframe in the original post:
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))
转换为 POSIXct 和 POSIXt 类(两种方法)
Convert to POSIXct and POSIXt class (two ways to do this)
# 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)
现在,将时间提取为十进制小时
Now, extract time as decimal hours
# 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
证明这些方法是相同的:
Demonstrate that these approaches are equal:
identical(h.str, h.lub)
然后选择上述方法之一将十进制小时分配给foo$hr
:
Then choose one of above approaches to assign decimal hour to foo$hr
:
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 }
然后使用 ggplot2 包进行绘图:
then plot using the ggplot2 package:
library(ggplot2)
qplot(foo$hr, foo$duration) +
scale_x_datetime(labels = "%S:00")
这篇关于从 POSIXct 中提取小时和秒以在 R 中绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!