2017-04-18 136 views
0

我已这需要起点 - 终点一个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中)在矩阵中相等的行。例如:

更新df中所有行的od_flows_all_combos [1,1]与287.5775等等。

我想通过行“循环”data.frame od_flows,从而使用应用函数。这只是一个例子。我的实际od_flow data.frame有dim(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

您可以组织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 
+0

或者,如果有很多零值的稀疏矩阵,而不是https://stat.ethz.ch/R -manual/R-devel/library/Matrix/html/sparseMatrix.html – zeehio

+0

我的目标是进一步使用我的od_flows_all_combos矩阵进行空间回归。 OD矩阵通常是稀疏矩阵,因此我需要更新od_flows_all_combos矩阵来表示我国的城市之间的流量。无论如何,Thx! – thoscha

+0

好的,找到了一个简单的解决方案:dcast函数做我需要的一切:'dcast(od_flows,destination〜origin)' – thoscha