简体   繁体   English

从 DF 在 R 中制作 O/D 表

[英]Make an O/D table in R from a DF

Good evening everyone.各位晚上好。 I'm having some trouble creating an O/D based on my DF.我在创建基于我的 DF 的 O/D 时遇到了一些麻烦。 My DF has the number of the trip, the index of each stop, the time od departure from each stop and the stops name:我的 DF 有行程编号、每个站点的索引、每个站点的出发时间和站点名称:

Trip Index Time OD
16   1     a    A
16   10    b    B
16   20    c    C
32   1     d    B
32   9     e    A
32   13    f    C
32   24    g    D

I need to have and O/D table, where I have the Origin's stop name |我需要有 O/D 表,其中有 Origin 的站点名称 | Destination's stop name |目的地的站点名称 | and Time of departure (Time in the DF) for each connection:每个连接的出发时间(DF 中的时间):

O D Time
A B a
A C a
B C b
B A d
B C d
B D d
A C e
A D e
C D f

Taking the first trip as an example.以第一次旅行为例。 It starts in stop "A" and ends inn stop "C" going through stop "B".它从“A”站开始,到经过“B”站的客栈“C”站结束。 So, for passengers in "A", they start their journey to "B" at time "a" and their journey to "C" at same time "a".因此,对于“A”中的乘客,他们在“a”时间开始前往“B”的旅程,并在“a”时间开始前往“C”的旅程。 For passengers in "B", they start their journey to "C" at time "b".对于“B”中的乘客,他们在“b”时间开始前往“C”的旅程。 From "C" you can't go nowhere with this trip.从“C”开始,这次旅行你不能 go 无处可去。 Then we must see the next trip.然后我们必须看到下一次旅行。 And so on.等等。

I've started to try with "for" loops and if else inside the for to start comparing the first line of the first trip with the second and third, then the second line of the first trip with the third, than passing to the next trip since there is no 4th leg.我已经开始尝试使用“for”循环,如果在 for 内有 else 开始比较第一次行程的第一行与第二次和第三次,然后将第一次行程的第二行与第三次进行比较,而不是传递到下一个旅行,因为没有第四站。 At least this is my rationale, don't know if it is clear or if it even makes sense.至少这是我的理由,不知道是否清楚,甚至是否有意义。

Thank you!谢谢!

Try this, with one simple helper-function:试试这个,用一个简单的辅助函数:

library(dplyr)
odfunc <- function(tm, od) {
  mtx <- t(combn(length(od), 2))
  tibble::tibble(O = od[mtx[,1]], D = od[mtx[,2]], Time = tm[mtx[,1]])
}

df %>%
  group_by(Trip) %>%
  do(with(., odfunc(Time, OD))) %>%
  ungroup()
# # A tibble: 9 x 4
#    Trip O     D     Time 
#   <int> <chr> <chr> <chr>
# 1    16 A     B     a    
# 2    16 A     C     a    
# 3    16 B     C     b    
# 4    32 B     A     d    
# 5    32 B     C     d    
# 6    32 B     D     d    
# 7    32 A     C     e    
# 8    32 A     D     e    
# 9    32 C     D     f    

Data:数据:

df <- read.table(header=TRUE, text="
Trip Index Time OD
16   1     a    A
16   10    b    B
16   20    c    C
32   1     d    B
32   9     e    A
32   13    f    C
32   24    g    D")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM