考虑以下示例
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
我想获得value
和difftime
的散点图,其中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.
但保持秒表示。
有什么想法吗? 谢谢!
答案 0 :(得分:3)
您可以使用attributes
函数修改difftime
对象的单位:
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"
使用attributes
更改单位:
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")