从POSIXct中提取时间和秒数,用于在R中绘制目的 [英] extract hours and seconds from POSIXct for plotting purposes in R
问题描述
假设我有以下 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)
返回
And class(foo$start.time)
returns
[1] "POSIXct" "POSIXt"
我想创建一个 foo $ duration
v。 foo $ start.time
。在我的情况下,我只对一天中的时间而不是一年的实际日子感兴趣。如何在一小时内提取时间:从
POSIXct
向量的类中的时间?
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包非常方便,所以下面我提出两种方法,一种使用base(由@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
证明这些方法相同:
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包绘图: / p>
then plot using the ggplot2 package:
library(ggplot2)
qplot(foo$hr, foo$duration) +
scale_x_datetime(labels = "%S:00")
这篇关于从POSIXct中提取时间和秒数,用于在R中绘制目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!