如何从R中的Datetime变量中仅提取时间参数?

时间:2015-03-29 06:46:58

标签: r datetime posixct posixlt

在R数据帧中,我有时间变量。数据格式为%a-%b-%d%H:%M:%S。例如,

2015-03-23 20:00:00

我想仅获取以下数据

  20:00:00

我已经创建了一个基于上述变量的表格并尝试制作折线图:

                     Var1 Var2  Freq
    1 2015-03-24 00:00:00   RT   612
    2 2015-03-24 01:00:00   RT    65
    3 2015-03-24 06:00:00   RT    58
    4 2015-03-24 07:00:00   RT  5132
    5 2015-03-24 08:00:00   RT  4483
    6 2015-03-24 09:00:00   RT 11112

我使用以下代码制作ggplot折线图:

   library(ggplot2)
   library(stringr)
   ggplot(rtt, aes(x = as.factor(Var1), y = Freq, colour = Var2, group = Var2)) + geom_line(size = 1) +
    xlab("R Vs T") + geom_point() +
    scale_x_discrete(labels = function(x) str_wrap(x, width = 2)) +
    ggtitle("Number of T Vs R - through the day") +
    theme(plot.title=element_text(size=rel(1.2), lineheight = 1 ))

如何从中删除YMD数据,因为我只想要时间而不是x轴中的数据,图中的x轴看起来完全乱码。

2 个答案:

答案 0 :(得分:1)

有很多选项可以提取'时间'部分。一些列在下面:

 format(as.POSIXct(str1), '%H:%M:%S')
 [1] "20:00:00"

或者

 sub('[^ ]+ ', '', str1)
 #[1] "20:00:00"

或者

 strftime(str1, format='%H:%M:%S')
 #[1] "20:00:00"

或者

 library(lubridate)
 format(ymd_hms(str1), '%H:%M:%S')
 #[1] "20:00:00"

ggplot代码可以更改为

 library(ggplot2)
 ggplot(rtt, aes(x= factor(strftime(Var1, format='%H:%M:%S')),
     y= Freq, colour=Var2, group=Var2)) +
     xlab("R Vs T") +
     geom_point() + 
     scale_x_discrete(labels = function(x) str_wrap(x, width = 2)) +
     ggtitle("Number of T Vs R - through the day") +
     theme(plot.title=element_text(size=rel(1.2), lineheight = 1 ))

更新

如果您只需要提取'小时'部分

 library(lubridate)
 hour(ymd_hms(str1))
 #[1] 20

数据

 str1 <- '2015-03-23 20:00:00'

 rtt <- structure(list(Var1 = c("2015-03-24 00:00:00", 
 "2015-03-24 01:00:00", 
 "2015-03-24 06:00:00", "2015-03-24 07:00:00", "2015-03-24 08:00:00", 
 "2015-03-24 09:00:00"), Var2 = c("RT", "RT", "RT", "RT", "RT", 
 "RT"), Freq = c(612L, 65L, 58L, 5132L, 4483L, 11112L)), 
 .Names = c("Var1", "Var2", "Freq"), class = "data.frame",
  row.names = c(NA, -6L))

答案 1 :(得分:1)

由于时间只包括几小时:

library(ggplot2)
rtt$hour <- as.POSIXlt(rtt$Var1)$hour
ggplot(rtt, aes(hour, Freq, col = Var2)) + geom_line()

注意:我们将此用于rtt

Lines <- "Var1,Var2,Freq
2015-03-24 00:00:00,RT,612
2015-03-24 01:00:00,RT,65
2015-03-24 06:00:00,RT,58
2015-03-24 07:00:00,RT,5132
2015-03-24 08:00:00,RT,4483
2015-03-24 09:00:00,RT,11112"
rtt <- read.csv(text = Lines, as.is = TRUE)

enter image description here