R 合并类似行以创建时间序列

R 合并类似行以创建时间序列,r,dataframe,plot,ggplot2,R,Dataframe,Plot,Ggplot2,我试图用R来处理一些数据来显示汽车的时间序列。我想画出时间序列中每辆汽车的速度。我希望它看起来像下图。每条线代表不同的汽车 Cars Date Speed Yellow Car 2017-07-02 17:41:00 20 Green car 2017-07-08 05:01:35 30 Yellow Car 2017-07-08 05:03:31 10 Blue Car 2017-07-08 05:52:55 4 Green car 2017-07-08 10:2

我试图用R来处理一些数据来显示汽车的时间序列。我想画出时间序列中每辆汽车的速度。我希望它看起来像下图。每条线代表不同的汽车

Cars    Date    Speed
Yellow Car  2017-07-02 17:41:00 20
Green car   2017-07-08 05:01:35 30
Yellow Car  2017-07-08 05:03:31 10
Blue Car    2017-07-08 05:52:55 4
Green car   2017-07-08 10:21:57 2
Green car   2017-07-08 12:07:51 12
期望输出:


您的数据集不完整,但您可以从以下示例中了解到这一点:

ggplot(df, aes(x=Time, y=Speed, group=Cars, color=Cars)) + geom_line() + 
              scale_colour_manual(values=c("blue", "green", "yellow"))

数据:

这与您的数据不同(它有不同的列),但看起来很像

df <- structure(list(Cars = structure(c(3L, 2L, 3L, 1L, 2L, 1L), .Label = c("BlueCar", 
"Greencar", "YellowCar"), class = "factor"), Date = structure(c(1L, 
1L, 1L, 1L, 1L, 2L), .Label = c("2017-07-08", "207-07-08"), class = "factor"), 
Time = structure(c(6L, 1L, 2L, 3L, 4L, 5L), .Label = c("05:01:35", 
"05:03:31", "05:52:55", "10:21:57", "12:07:51", "17:41:00"
), class = "factor"), Speed = c(20L, 30L, 10L, 4L, 2L, 15L)),
.Names = c("Cars", "Date", "Time", "Speed"), class = "data.frame", row.names = c(NA,-6L))

df您的数据集不完整,但您可以从以下示例中了解到这一点:

ggplot(df, aes(x=Time, y=Speed, group=Cars, color=Cars)) + geom_line() + 
              scale_colour_manual(values=c("blue", "green", "yellow"))

数据:

这与您的数据不同(它有不同的列),但看起来很像

df <- structure(list(Cars = structure(c(3L, 2L, 3L, 1L, 2L, 1L), .Label = c("BlueCar", 
"Greencar", "YellowCar"), class = "factor"), Date = structure(c(1L, 
1L, 1L, 1L, 1L, 2L), .Label = c("2017-07-08", "207-07-08"), class = "factor"), 
Time = structure(c(6L, 1L, 2L, 3L, 4L, 5L), .Label = c("05:01:35", 
"05:03:31", "05:52:55", "10:21:57", "12:07:51", "17:41:00"
), class = "factor"), Speed = c(20L, 30L, 10L, 4L, 2L, 15L)),
.Names = c("Cars", "Date", "Time", "Speed"), class = "data.frame", row.names = c(NA,-6L))

df伙计,这真是帮了大忙!还有一个问题,如果我想在x轴内表示日期和时间,该怎么办。我偶然发现as.POSIXlt似乎采用了这种UTC格式,我该如何在这里实现它?@AnthonyM添加这个
+scale\u x\u datetime(breaks=Date,labels=format(Date,“%Y-%m-%d%H:%m:%S”)
Dude这真是太棒了!还有一个问题,如果我想在x轴内表示日期和时间,该怎么办。我偶然发现as.POSIXlt似乎采用了UTC格式,我该如何在这里实现它?@AnthonyM添加这个
+scale\u x\u datetime(breaks=date,labels=format(date),%Y-%m-%d%H:%m:%S”)