我有一个data.frame需要源 - 目标流:
#od flows data.frame with trips per year as flows
set.seed(123)
origin <- c(rep(1,3),rep(2,3),rep(3,3))
destination <- c(rep(1:3,3))
flow <- c(runif(9, min=0, max=1000))
od_flows <- data.frame(origin,destination,flow)
# od matrix with all possible origins and destinations
od_flows_all_combos <- matrix(0,10,10)
od_flows
od_flows_all_combos
> od_flows
origin destination flow
1 1 1 287.5775
2 1 2 788.3051
3 1 3 408.9769
4 2 1 883.0174
5 2 2 940.4673
6 2 3 45.5565
7 3 1 528.1055
8 3 2 892.4190
9 3 3 551.4350
> od_flows_all_combos
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 0 0 0 0 0 0 0 0 0 0
[2,] 0 0 0 0 0 0 0 0 0 0
[3,] 0 0 0 0 0 0 0 0 0 0
[4,] 0 0 0 0 0 0 0 0 0 0
[5,] 0 0 0 0 0 0 0 0 0 0
[6,] 0 0 0 0 0 0 0 0 0 0
[7,] 0 0 0 0 0 0 0 0 0 0
[8,] 0 0 0 0 0 0 0 0 0 0
[9,] 0 0 0 0 0 0 0 0 0 0
[10,] 0 0 0 0 0 0 0 0 0 0
我想用od_flows data.frame的值更新od_flows_all_combos矩阵,使得原点值(以df为单位)等于列号(在矩阵中)和目标值(以df为单位)在矩阵中等于行。例如:
使用287.5775更新od_flows_all_combos [1,1],依此类推df中的所有行。
我想按行“循环”data.frame od_flows,从而使用apply-function。这只是一个例子。我的实际od_flow data.frame有暗淡(1'200'000 x 3)和矩阵(2886x2886)。所以我需要一个有效的方法解决这个问题。
我的第一个方法是:
for(i in 1:nrow(od_flows)){
od_flows_all_combos[rownames(od_flows_all_combos)==od_flows[i,2],colnames(od_flows_all_combos)==od_flows[i,1]] <- od_flows[i,3]
}
计算尚未结束......
有人可以使用应用功能帮助我解决方案吗?
谢谢!
答案 0 :(得分:0)
您可以直接将od_flows数据框组织为矩阵,假设od_flows
完全填充your_desired_matrix
require(dplyr)
set.seed(123)
origin <- c(rep(1,3),rep(2,3),rep(3,3))
destination <- c(rep(1:3,3))
flow <- c(runif(9, min=0, max=1000))
od_flows <- data.frame(origin,destination,flow)
od_flows_order = od_flows %>% arrange(origin, destination)
your_desired_matrix = matrix(od_flows_order$flow, ncol = 3, byrow = TRUE)
your_desired_matrix
[,1] [,2] [,3]
[1,] 287.5775 788.3051 408.9769
[2,] 883.0174 940.4673 45.5565
[3,] 528.1055 892.4190 551.4350