Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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. </p> <p>Recreate the (first two rows of) the dataframe in the original post:</p> <pre><code>foo &lt;- 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)) </code></pre> <p>Convert to POSIXct and POSIXt class (two ways to do this)</p> <pre><code># using base::strptime t.str &lt;- strptime(foo$start.time, "%Y-%m-%d %H:%M:%S") # using lubridate::ymd_hms library(lubridate) t.lub &lt;- ymd_hms(foo$start.time) </code></pre> <p>Now, extract time as decimal hours</p> <pre><code># using base::format h.str &lt;- as.numeric(format(t.str, "%H")) + as.numeric(format(t.str, "%M"))/60 # using lubridate::hour and lubridate::minute h.lub &lt;- hour(t.lub) + minute(t.lub)/60 </code></pre> <p>Demonstrate that these approaches are equal:</p> <pre><code>identical(h.str, h.lub) </code></pre> <p>Then choose one of above approaches to assign decimal hour to <code>foo$hr</code>:</p> <pre><code>foo$hr &lt;- h.str # If you prefer, the choice can be made at random: foo$hr &lt;- if(runif(1) &gt; 0.5){ h.str } else { h.lub } </code></pre> <p>then plot using the ggplot2 package:</p> <pre><code>library(ggplot2) qplot(foo$hr, foo$duration) +           scale_x_datetime(labels = "%S:00") </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload