Consider the following example
time = c('2013-01-03 22:04:21.549', '2013-01-03 22:04:21.549', '2013-01-03 22:04:21.559', '2013-01-03 22:04:23.559' )
ref = c('2013-01-03 22:04:20', '2013-01-03 22:04:20', '2013-01-03 22:04:20', '2013-01-03 22:04:20')
value = c(1,2,3,4)
data <- data_frame(time, ref, value)
data <-data %>% mutate(time = ymd_hms(time),
ref = ymd_hms(ref),
difftime = time - ref)
# A tibble: 4 × 4
time ref value difftime
<dttm> <dttm> <dbl> <time>
1 2013-01-03 22:04:21 2013-01-03 22:04:20 1 1.549 secs
2 2013-01-03 22:04:21 2013-01-03 22:04:20 2 1.549 secs
3 2013-01-03 22:04:21 2013-01-03 22:04:20 3 1.559 secs
4 2013-01-03 22:04:23 2013-01-03 22:04:20 4 3.559 secs
I would like to get a scatterplot of value
and difftime
where the units of difftime
are in milliseconds.
I dont know how to do that. The best I could do is the following:
ggplot(data, aes(x = value, y = difftime )) + geom_point()
Don't know how to automatically pick scale for object of type difftime. Defaulting to continuous.
but that keeps the seconds representation.
Any ideas? Thanks!!
You can use attributes
function to modify the units of difftime
object:
time = c('2013-01-03 22:04:21.549', '2013-01-03 22:04:21.549', '2013-01-03 22:04:21.559', '2013-01-03 22:04:23.559' )
ref = c('2013-01-03 22:04:20', '2013-01-03 22:04:20', '2013-01-03 22:04:20', '2013-01-03 22:04:20')
value = c(1,2,3,4)
library("dplyr")
library("ggplot2")
library("lubridate")
DF <- data.frame(time, ref, value)
DF <- DF %>% mutate(time = ymd_hms(time),
ref = ymd_hms(ref),
delta_time_secs = time - ref)
attributes(DF$delta_time_secs)
#
#$units
#[1] "secs"
#
#$class
#[1] "difftime"
Using attributes
to change units:
DF <- DF %>% mutate(delta_time_msecs = (time - ref)*1000)
attributes(DF$delta_time_msecs)$units="milliseconds"
attributes(DF$delta_time_msecs)
#$units
#[1] "milliseconds"
#
#$class
#[1] "difftime
DF
# time ref value delta_time_secs delta_time_msecs
#1 2013-01-03 22:04:21 2013-01-03 22:04:20 1 1.549 secs 1549 milliseconds
#2 2013-01-03 22:04:21 2013-01-03 22:04:20 2 1.549 secs 1549 milliseconds
#3 2013-01-03 22:04:21 2013-01-03 22:04:20 3 1.559 secs 1559 milliseconds
#4 2013-01-03 22:04:23 2013-01-03 22:04:20 4 3.559 secs 3559 milliseconds
ggplot(DF, aes(x = value, y = as.numeric(delta_time_msecs))) + geom_point() + ylab("Time in milliseconds")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With