在R中创建Origin-Destination表

时间:2013-12-03 05:31:39

标签: r

我每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

1 个答案:

答案 0 :(得分: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