如何使用R将每小时的乘客OD数据传输到od矩阵

时间:2018-10-23 06:47:50

标签: r matrix reshape

我正在尝试将每小时的乘客OD数据传输到OD矩阵。

我当前的数据框看起来像这样:

Hour  Ostation Dstation  Passengers
8      A       B          2
8      A       C          3
8      A       D          4
8      B       C          5
8      B       D          6
8      C       D          1
10     A       B          4
10     A       C          5 
10     A       D          6 
10     B       C          1
10     B       D          2
10     C       D          3

我想购买HOUR = 8

    A   B   C   D
A       
B   2
C   3   5
D   4   6   1

还有HOUR = 10

    A   B   C   D
A       
B   4
C   5   1
D   6   2   3

我使用splittable

ODdata$Ostation <- factor(ODdata$Ostation)
ODdata$Dstation <- factor(ODdata$Dstation)
ODtable <-lapply(split(ODdata, ODdata$Hour), 
                 function(x) table(x$Ostation, x$Dstation))

我可以获得OD矩阵,但值是计数,而不是Passengers

1 个答案:

答案 0 :(得分:2)

您应使用dcast中的reshape2代替table。设置drop = F可将所有因子水平保留在输出矩阵中。

library(reshape2)
ODtable <-lapply(split(ODdata, ODdata$Hour), 
                 function(x) dcast(Dstation ~ Ostation , data = x, 
                                   value.var = "Passengers", drop = FALSE))
ODtable

#$`8`
#  Dstation  A  B  C  D
#1        A NA NA NA NA
#2        B  2 NA NA NA
#3        C  3  5 NA NA
#4        D  4  6  1 NA
# 
#$`10`
#  Dstation  A  B  C  D
#1        A NA NA NA NA
#2        B  4 NA NA NA
#3        C  5  1 NA NA
#4        D  6  2  3 NA

样本数据

ODdata <- data.frame(Hour = c(rep(8,6), rep(10,6)),
             Ostation = factor(c("A","A","A","B","B","C","A","A","A","B","B","C"),
                                   levels = c('A', 'B', 'C', 'D')),
             Dstation = factor(c("B","C","D","C","D","D","B","C","D","C","D","D"), 
                                   levels = c('A', 'B', 'C', 'D')),
             Passengers = c(2,3,4,5,6,1,4,5,6,1,2,3))