您的整个代码可以缩短为一行:
cbind(expand.grid(Destination = 1:4, Origin = 1:4)[2:1], Trip = as.vector(t(od_matrix)))
你还没有给我们od_matrix,所以我们假设它看起来像这样:
od_matrix <- matrix(1:16, nrow = 4)
od_matrix
#> [,1] [,2] [,3] [,4]
#> [1,] 1 5 9 13
#> [2,] 2 6 10 14
#> [3,] 3 7 11 15
#> [4,] 4 8 12 16
现在:
cbind(expand.grid(Destination = 1:4, Origin = 1:4)[2:1], Trip = as.vector(t(od_matrix)))
#> Origin Destination Trip
#> 1 1 1 1
#> 2 1 2 5
#> 3 1 3 9
#> 4 1 4 13
#> 5 2 1 2
#> 6 2 2 6
#> 7 2 3 10
#> 8 2 4 14
#> 9 3 1 3
#> 10 3 2 7
#> 11 3 3 11
#> 12 3 4 15
#> 13 4 1 4
#> 14 4 2 8
#> 15 4 3 12
#> 16 4 4 16
结果是一样的
df_trips <- data.frame(Origin=character(),
Destination=character(),
Trip=character(),
stringsAsFactors=FALSE)
for(i in 1:4){
for(j in 1:4){
Origin=i
Destination=j
Trip=od_matrix[i,j]
df_temp <- data.frame(Origin,Destination,Trip)
df_trips= rbind(df_trips,df_temp)
}
}
df_trips
#> Origin Destination Trip
#> 1 1 1 1
#> 2 1 2 5
#> 3 1 3 9
#> 4 1 4 13
#> 5 2 1 2
#> 6 2 2 6
#> 7 2 3 10
#> 8 2 4 14
#> 9 3 1 3
#> 10 3 2 7
#> 11 3 3 11
#> 12 3 4 15
#> 13 4 1 4
#> 14 4 2 8
#> 15 4 3 12
#> 16 4 4 16