【问题标题】:Creating a Unique Key in R for time series data based on a binary starttime and endtime columns基于二进制开始时间和结束时间列在 R 中为时间序列数据创建唯一键
【发布时间】:2018-12-08 10:56:11
【问题描述】:

我正在尝试为驾驶研究中的行程绘制车道数据。数据集如下所示: Dataset

使用以下代码,我能够为每次旅行创建图

library(ggplot2)
library(grid)

LaneData <- read.csv(file="c:\\Users\\jasonzb\\Desktop\\Cars overtaking trucks Project\\Honda Image\\Truck Overpassing Event Device 10150.csv", header=TRUE, sep=",")
LaneData <- cbind(LaneData[,1:3], LaneData[,7:8])

#rename first column
colnames(LaneData)[1] <- "device"

#Create segment to split data by
LaneData$SplitID <- seq.int(nrow(LaneData))
LaneData$SplitID = round(LaneData$SplitID, digits = -4)

#melt the data
LaneData <-melt(LaneData, id=c("device", "trip", "time", "SplitID"))

#Create levels for SplitID
LaneData$SplitID = factor(LaneData$SplitID)

for (i in levels(LaneData$SplitID)){
   LaneData_temp <- subset(LaneData, LaneData$SplitID == i)  
   print(ggplot(LaneData_temp, aes(LaneData_temp$value, LaneData_temp$time, col =LaneData_temp$variable)) + geom_point() + facet_wrap(~ trip, scales = "free"))
}

这会产生如下所示的图: Plots

对于右边的情节(Trip 5820),一切看起来都很好。然而,对于右边的图(Trip 5813),由于数据中的差距,有几个不同间隔的时间序列事件组合在一起,如下所示:Dataset: Time series Break

有没有办法创建一个唯一键来分隔时间戳中的变化,以便可以单独绘制每个时间序列数据段?

谢谢!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    考虑创建一个新列作为 time 变量的乘积。然后运行多个变量facet_wrapfacet_grid。例如:

    time <- c(523490 + seq(0, 70, 10), 764350 + seq(0, 50, 10))
    time
    # [1] 523490 523500 523510 523520 523530 523540 523550 523560 764350 764360 764370 764380 764390 764400
    
    # THOUSAND MULTIPLIERS
    time_grp <- as.integer(time / 10000)
    time_grp
    # [1] 52 52 52 52 52 52 52 52 76 76 76 76 76 76
    
    # TEN-THOUSAND MULTIPLIERS
    time_grp <- as.integer(time / 100000)
    time_grp
    # [1] 5 5 5 5 5 5 5 5 7 7 7 7 7 7
    

    要集成到当前代码中,请将最后一个 for 循环替换为 by 以将数据帧拆分为子集以进行绘图:

    ...
    by(LaneData, LaneData$SplitID, function(sub) {
       sub$time_grp <- as.integer(sub$time / 10000)
    
       ggplot(sub, aes(value, time, col=variable)) + geom_point() +
           facet_wrap(trip ~ time_grp, scales = "free")
           # TRY: facet_grid(. ~ time_grp + trip, scales = "free")
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-06
      • 2017-11-04
      • 2012-06-27
      • 1970-01-01
      • 1970-01-01
      • 2012-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多