Convert an edge list with properties to a matrix
Source:R/edge_properties.R
edge_properties_to_matrix.RdA utility function to convert a data frame of edge properties
(e.g., movement rates, counts) into the specific matrix format
required for ldata in spatial models. This format allows
the C code to efficiently iterate over all incoming edges for a
specific node.
Value
A numeric matrix with dimensions determined by the maximum
number of incoming edges for any node. Columns correspond to
to nodes. Entries are NaN where no data exists.
Details
The function converts the edges data frame into a numeric
matrix where:
Each column corresponds to a
tonode.Each column contains a single sequence of data blocks, one for each incoming edge to that node.
Each block starts with the zero-based index of the
fromnode.The subsequent rows in the block contain the property values (e.g., rate, count).
The sequence for a node ends with a stop marker (
-1) in the first row of the block (the position where thefromindex is stored). This marker appears exactly once per column, immediately after the last incoming edge.Unused cells in the matrix (below the stop marker) are filled with
NaN.
The edges data frame must contain columns from and
to with valid node indices (1-based). All edges pointing to
the same to node must be unique (no duplicate from ->
to pairs).
Examples
## Define edge properties: from, to, rate, and count.
edges <- data.frame(
from = c(2, 3, 4, 1, 4, 5, 1, 3, 1, 3),
to = c(1, 1, 1, 2, 3, 3, 4, 4, 5, 5),
rate = c(0.2, 0.01, 0.79, 1, 0.2, 0.05, 0.2, 0.8, 0.2, 0.8),
count = c(5, 5, 5, 50, 10, 10, 5, 5, 5, 5)
)
## Convert to matrix for 6 nodes.
mat <- edge_properties_to_matrix(edges, 6)
print(mat)
#> [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,] 1.00 0 3.00 0.0 0.0 -1
#> [2,] 0.20 1 0.20 0.2 0.2 NaN
#> [3,] 5.00 50 10.00 5.0 5.0 NaN
#> [4,] 2.00 -1 4.00 2.0 2.0 NaN
#> [5,] 0.01 NaN 0.05 0.8 0.8 NaN
#> [6,] 5.00 NaN 10.00 5.0 5.0 NaN
#> [7,] 3.00 NaN -1.00 -1.0 -1.0 NaN
#> [8,] 0.79 NaN NaN NaN NaN NaN
#> [9,] 5.00 NaN NaN NaN NaN NaN
#> [10,] -1.00 NaN NaN NaN NaN NaN
## Interpretation of Column 1 (to node 1): The column contains a
## single sequence of 3 blocks (edges from # 2, 3, and 4).
## Row 1: Index of 'from' node 2 (2-1 = 1).
## Row 2: rate=0.2
## Row 3: count=5
## Row 4: Index of 'from' node 3 (3-1 = 2).
## Row 5: rate=0.01
## Row 6: count=5
## Row 7: Index of 'from' node 4 (4-1 = 3).
## Row 8: rate=0.79
## Row 9: count=5
## Row 10: Stop marker (-1) indicating the end of the list for node 1.