lubridate:如何将 difftime 转换为毫秒单位(并绘制它)?

ℕʘʘ*_*ḆḽḘ 5 datetime r ggplot2 lubridate

考虑下面的例子

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
Run Code Online (Sandbox Code Playgroud)

我想获得的散点图valuedifftime地方的单位difftime毫秒

我不知道该怎么做。我能做的最好的是以下几点:

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.
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

但这保留了秒表示。

有任何想法吗?谢谢!!

Sil*_*ood 6

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"
Run Code Online (Sandbox Code Playgroud)

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")  
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • 恕我直言,这太复杂了。你为什么不直接做 `ggplot(DF, aes(x = value, y = as.numeric(delta_time_secs) * 1000)) + ...` 而不像 Jaap 建议的那样改变 `DF`? (2认同)