Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)

How would I extract the time from a series of POSIXct objects discarding the date part?

For instance, I have:

times <- structure(c(1331086009.50098, 1331091427.42461, 1331252565.99979, 

1331252675.81601, 1331262597.72474, 1331262641.11786, 1331269557.4059, 

1331278779.26727, 1331448476.96126, 1331452596.13806), class = c("POSIXct", 

"POSIXt"))

which corresponds to these dates:

"2012-03-07 03:06:49 CET" "2012-03-07 04:37:07 CET" 

"2012-03-09 01:22:45 CET" "2012-03-09 01:24:35 CET" 

"2012-03-09 04:09:57 CET" "2012-03-09 04:10:41 CET"

"2012-03-09 06:05:57 CET" "2012-03-09 08:39:39 CET"

"2012-03-11 07:47:56 CET" "2012-03-11 08:56:36 CET"

Now, I have some values for a parameter measured at those times

val <- c(1.25343125e-05, 0.00022890575, 

         3.9269125e-05, 0.0002285681875, 

         4.26353125e-05, 5.982625e-05, 

         2.09575e-05, 0.0001516951251, 

         2.653125e-05, 0.0001021391875)

I would like to plot val vs time of the day, irrespectively of the specific day when val was measured.

Is there a specific function that would allow me to do that?

1 Answer

0 votes
by

To convert datetimes to any character format, you can use the strftime function as follows:

times <- structure(c(1331086009.50098, 1331091427.42461, 1331252565.99979, 

                     1331252675.81601, 1331262597.72474, 1331262641.11786, 1331269557.4059, 

                     1331278779.26727, 1331448476.96126, 1331452596.13806), class = c("POSIXct", 

                                                                                      "POSIXt"))

t <- strftime(times, format="%H:%M:%S")

Output:

 [1] "07:36:49" "09:07:07" "05:52:45" "05:54:35" "08:39:57" "08:40:41" "10:35:57"

 [8] "13:09:39" "12:17:56" "13:26:36"

Since you want to plot your data.One way is to strip the date element from your times, and then to add an identical date to all of your times.i.e.,

dt <- as.POSIXct(t, format="%H:%M:%S")

> dt

 [1] "2019-07-25 07:36:49 IST" "2019-07-25 09:07:07 IST" "2019-07-25 05:52:45 IST"

 [4] "2019-07-25 05:54:35 IST" "2019-07-25 08:39:57 IST" "2019-07-25 08:40:41 IST"

 [7] "2019-07-25 10:35:57 IST" "2019-07-25 13:09:39 IST" "2019-07-25 12:17:56 IST"

[10] "2019-07-25 13:26:36 IST"

To plot the datetime objects:

plot(dt, rnorm(length(dt)), xlab="Time", ylab="Random value")

Output:

image

Browse Categories

...