[英]How to create a matrix with 1s and 0s based off a 2-column data frame
Here is an example of what my data looks like (what I have is actually 1300 lines, or 1300 connections/edges between two different nodes): 以下是我的数据的示例(我拥有的实际是1300行,或两个不同节点之间的1300个连接/边):
node# node#
1 3
1 4
2 4
2 5
3 4
3 5
I currently have the above data in a data frame. 我目前在数据框中有上述数据。 This represent a network where a car can drive from node 1 to 3 or 1 to 4, and from node 2 to 4 or node 2 to 5, etc. I'd like to create a matrix that looks like this: 这代表一个网络,汽车可以从节点1驱动到3或1到4,从节点2到4或节点2到5等。我想创建一个如下所示的矩阵:
> [,1] [,2] [,3] [,4] [,5] [,6]
[1,] 0 0 0 0 0 0
[2,] 0 0 0 0 0 0
[3,] 0 0 0 0 0 0
[4,] 0 0 0 0 0 0
[5,] 0 0 0 0 0 0
Where I'm stuck: I want to input 1s into the matrix from the leaving node, and a -1 in the matrix of the destination node, in the same column. 我被卡住的地方:我想在离开节点的矩阵中输入1,在同一列中输入目标节点矩阵中的-1。 So for this 6 node-connection data frame, the matrix would look like: 因此对于这个6节点连接数据帧,矩阵看起来像:
> [,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 1 0 0 0 0
[2,] 0 0 1 1 0 0
[3,] -1 0 0 0 1 1
[4,] 0 -1 -1 0 -1 0
[5,] 0 0 0 -1 0 -1
But like I said, I have more than 1300 connections, so doing this by hand would take a while. 但就像我说的,我有超过1300个连接,所以用手做这个需要一段时间。 So I'm guessing matrix(0, 5, 1300) would be where I start? 所以我猜测矩阵(0,5,1300)将是我开始的地方?
You can index specific row/column pairs of a matrix using a 2-column indexing matrix. 您可以使用2列索引矩阵索引矩阵的特定行/列对。 This provides a convenient way to set all the 1's and then set all the -1's: 这提供了一种方便的方法来设置所有的1,然后设置所有-1的:
mat <- matrix(0, nrow=max(dat), ncol=nrow(dat))
mat[cbind(dat$node1, seq_len(nrow(dat)))] <- 1
mat[cbind(dat$node2, seq_len(nrow(dat)))] <- -1
mat
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] 1 1 0 0 0 0
# [2,] 0 0 1 1 0 0
# [3,] -1 0 0 0 1 1
# [4,] 0 -1 -1 0 -1 0
# [5,] 0 0 0 -1 0 -1
(Thanks to @PierreLafortune for the trick about calling max
on a data frame!) (感谢@PierreLafortune关于在数据帧上调用max
的技巧!)
Data: 数据:
dat <- data.frame(node1=c(1, 1, 2, 2, 3, 3), node2=c(3, 4, 4, 5, 4, 5))
We could also use sparseMatrix
from library(Matrix)
我们也可以使用library(Matrix)
sparseMatrix
library(Matrix)
library(Matrix)
B <- sparseMatrix(dat$node2, seq_len(nrow(dat)), x= -1)
mat <- sparseMatrix(dat$node1, seq_len(nrow(dat)), x= 1,
dims=dim(B)) + B
as.matrix(mat)
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 1 1 0 0 0 0
#[2,] 0 0 1 1 0 0
#[3,] -1 0 0 0 1 1
#[4,] 0 -1 -1 0 -1 0
#[5,] 0 0 0 -1 0 -1
NOTE: dat
taken from @josliber's post. 注意: dat
取自@ josliber的帖子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.