【问题标题】:Creating a Origin-Destination Table in R在 R 中创建起点-终点表
【发布时间】:2013-12-03 14:01:23
【问题描述】:

我有一个每 0.1 秒记录一次的大型车辆数据集,如下所示:

   id frame lane class
1   2    13    1     1
2   2    14    1     1
3   2    15    2     1
4   2    16    2     1
5   4    18    3     3
6   4    19    3     3
7   4    20    3     3
8   5    15    2     2
9   5    16    2     2
10  5    17    2     2
11  5    18    3     2
12  5    19    3     2
13  6    14    1     3
14  6    15    1     3
15  6    16    1     3
16  6    17    2     3
17  6    18    2     3

'frame'为录像帧ID,'lane'为车辆占用的车道#,'class'为车辆分类,即1=摩托车,2=汽车,3=卡车。

需要的输出

我想在以下四列中查找第一次和最后一次出现的车辆 ID 及其相关数据:

id 
Origin (lane # in the first occurrence of id) 
Destination (lane # in the last occurrence of id) 
class

到目前为止我所做的尝试:

(注意输入表是“输入”数据框)

input$first <- !duplicated(input$'id') 
input$last <- !duplicated(input$'id', fromLast=T)
ODTable <- subset(input, m$'first'==T | m$'last'==T)

我得到了以下输出,它给了我正确的信息,但不是所需的格式:

ODTable


   id frame lane class first  last
1   2    13    1     1  TRUE FALSE
4   2    16    2     1 FALSE  TRUE
5   4    18    3     3  TRUE FALSE
7   4    20    3     3 FALSE  TRUE
8   5    15    2     2  TRUE FALSE
12  5    19    3     2 FALSE  TRUE
13  6    14    1     3  TRUE FALSE
17  6    18    2     3 FALSE  TRUE

【问题讨论】:

  • 您可能要考虑在此处使用data.table,因为它可以更清晰地过滤您的数据。与shiny 也一样

标签: r


【解决方案1】:
library(data.table)
input <- as.data.table(input)


setkey(input, "id")

# First
input[.(unique(id)), mult="first"]
   id frame lane class
1:  2    13    1     1
2:  4    18    3     3
3:  5    15    2     2
4:  6    14    1     3

# Last
input[.(unique(id)), mult="last"]
   id frame lane class
1:  2    16    2     1
2:  4    20    3     3
3:  5    19    3     2
4:  6    18    2     3

把它们放在一起:

first <- input[.(unique(id)) , mult="first"]
last <- input[.(unique(id)) ,  mult="last"]

Destination <- copy(first)[last, destin := i.lane]
Destination
   id frame lane class destin
1:  2    13    1     1      2
2:  4    18    3     3      3
3:  5    15    2     2      3
4:  6    14    1     3      2

【讨论】:

  • 除了最后两列之外,您的答案与我的相似,虽然它为我提供了所需的信息,但格式不正确。所需格式是问题中描述的格式。我需要“原点”列中车辆 ID 的第一行中的车道号和目的地列中相同车辆 ID 的第二行中的车道号(请参阅有问题的“所需输出”)。例如对于车辆 id 2,它应该如下所示: id=2 origin=1 destination=2 class=1
  • 类似:input[, list(origin=lane[1],destin=lane[.N],class=class[1]), by="id"] 也许?
  • @Ricardo 谢谢!我得到了我的 OD 表。 thelatemail 我也试试那个。
猜你喜欢
  • 1970-01-01
  • 2017-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-27
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
相关资源
最近更新 更多