Conversion & I/O API Reference
This page documents all conversion and I/O functions in NetworkCore.jl.
Network to Matrix
as_matrix
NetworkCore.as_matrix — Function
as_matrix(net::Network; attr=nothing, sparse=false, missing_value=nothing,
return_mask=false, expand_bipartite=false)Convert network to an adjacency matrix.
Two-mode networks
For a two-mode network (network(n; bipartite=n₁) or a BipartiteNetwork) the default is the n_mode1 × n_mode2 two-mode incidence matrix (rows = mode-1 vertices, columns = mode-2 vertices), matching R's as.matrix.network for bipartite networks. Pass expand_bipartite=true (R's expand.bipartite=) to get the full (n₁ + n₂)-square adjacency matrix instead — the mode-1 vertices in rows/columns 1:n₁, the mode-2 vertices after them, and the incidence block sitting at A[1:n₁, n₁+1:end] (mirrored into the lower block for an undirected network). That square matrix is what every one-mode matrix routine (eigenvector centrality, structural equivalence, QAP, ...) expects, and it round-trips through network_from_matrix. attr=, sparse=, missing_value= and return_mask= all apply to either shape.
On a directed two-mode network the incidence matrix can only represent arcs from mode 1 to mode 2 (B[i, j] is the arc i → k + j). An arc in the other direction (mode 2 → mode 1), and a mask on such a dyad, has no cell: exactly as R's as.matrix.network does, it is dropped from the incidence matrix (never written into the mirror cell as if it pointed the other way), and NetworkCore.jl additionally emits a @warn naming how many were dropped. Pass expand_bipartite=true for the square matrix that keeps every arc. On an undirected two-mode network the question does not arise.
Validation
attr= must name an existing edge attribute: as_matrix(net; attr=:wt) on a network whose only edge attribute is :weight throws an ArgumentError listing the attributes that exist, instead of returning the all-zero matrix that would feed silently into QAP or an eigenvector centrality downstream (R's as.sociomatrix warns "There is no edge attribute named wt"). An edge that exists but carries no value for attr contributes 0.
Missing dyads
By default the matrix carries only the face value of each dyad, so a masked (unobserved) dyad is indistinguishable from an absent tie and the mask is lost on conversion. Two keywords make the conversion lossless:
missing_value=missingmarks each masked dyad withmissing, giving an element type ofUnion{Missing,Float64}.network_from_matrixreads such a matrix back into a mask, sonetwork_from_matrix(as_matrix(net; missing_value=missing))round-trips. Any other value (e.g.NaN,-1) is written literally instead.return_mask=truereturns(A, mask)wheremask[i,j]istruefor the masked dyads, leavingAnumeric.
Arguments
net::Network: The network to convertattr::Union{Symbol,Nothing}=nothing: Edge attribute to use as values (nothing = binary)sparse::Bool=false: Return a sparse matrix instead of densemissing_value=nothing: value written at masked dyads (nothing= face value)return_mask::Bool=false: also return theBitMatrixof masked dyadsexpand_bipartite::Bool=false: on a two-mode network, return the(n₁ + n₂)-square adjacency matrix instead of then₁ × n₂incidence matrix
Example
net = network(4)
add_edges!(net, [(1, 2), (2, 3)])
set_edge_attribute!(net, :weight, 1, 2, 2.0)
set_missing_dyad!(net, 3, 4) # 3→4 is unobserved
A = as_matrix(net) # face values: A[3,4] == 0
W = as_matrix(net; attr=:weight) # W[1,2] == 2.0, W[2,3] == 0.0
M = as_matrix(net; missing_value=missing) # lossless: M[3,4] === missing
A, mask = as_matrix(net; return_mask=true) # mask[3,4] == true
b = network(5; bipartite=2, directed=false)
add_edge!(b, 1, 3)
size(as_matrix(b)) # (2, 3) — incidence matrix
size(as_matrix(b; expand_bipartite=true)) # (5, 5) — square adjacency matrix
d = network(5; bipartite=2, directed=true)
add_edges!(d, [(1, 3), (4, 2)])
as_matrix(d) # 2×3 with B[1,1] = 1 only; warns that 4→2 was dropped
as_matrix(d; expand_bipartite=true)[4, 2] # 1.0 — the square matrix keeps itas_adjacency_matrix
NetworkCore.as_adjacency_matrix — Function
as_adjacency_matrix(net::Network; kwargs...) -> MatrixAlias for as_matrix, taking the same keywords (attr=, sparse=, missing_value=, return_mask=, expand_bipartite=). Matches R's as.matrix.network with matrix.type="adjacency".
Example
net = network(3; directed=false)
add_edge!(net, 1, 2)
as_adjacency_matrix(net) == as_matrix(net) # true
as_adjacency_matrix(net)[1, 2] # 1.0Network to Edge List
as_edgelist
NetworkCore.as_edgelist — Function
as_edgelist(net::Network; attrs::Vector{Symbol}=Symbol[]) -> MatrixConvert network to an edge list (n_edges x 2 matrix), one row per edge in edges(net) order (each undirected edge once, src <= dst), matching R's as.edgelist.
Arguments
net::Network: The network to convertattrs::Vector{Symbol}: Edge attributes to include as additional columns. Every name must be an existing edge attribute (ArgumentErrorlisting the attributes that exist otherwise — a mistyped name used to return a column ofmissingsilently); an edge that carries no value for an attribute getsmissing.
Returns
If no attrs: Matrix{Int} of size (nedges, 2) If attrs: Returns a tuple (edgelist::Matrix{Int}, attrvalues::Dict{Symbol, Vector})
Example
net = network(3)
add_edges!(net, [(1, 2), (2, 3)])
set_edge_attribute!(net, :weight, 1, 2, 2.5)
as_edgelist(net) # [1 2; 2 3]
el, vals = as_edgelist(net; attrs=[:weight])
vals[:weight] # Any[2.5, missing]
try as_edgelist(net; attrs=[:wt]) catch err; err end # ArgumentError: no edge attribute :wtNetwork to DataFrame
as_dataframe
NetworkCore.as_dataframe — Function
as_dataframe(net::Network; vertices::Bool=false, attrs::Vector{Symbol}=Symbol[]) -> DataFrameConvert network to a DataFrame.
Requires DataFrames.jl to be loaded (using DataFrames); the method is provided by the NetworkDataFramesExt package extension.
Arguments
net::Network: The network to convertvertices::Bool=false: If true, return vertex DataFrame instead of edge DataFrameattrs::Vector{Symbol}: Attributes to include (defaults to all)
Example
using NetworkCore, DataFrames
net = network(3)
add_edges!(net, [(1, 2), (2, 3)])
set_edge_attribute!(net, :weight, 1, 2, 2.5)
set_vertex_attribute!(net, :name, Dict(1 => "a", 2 => "b", 3 => "c"))
edge_df = as_dataframe(net) # columns source, target, weight
edge_df.weight # [2.5, missing]
vertex_df = as_dataframe(net; vertices=true) # columns vertex, name
vertex_df.name # ["a", "b", "c"]Matrix to Network
network_from_matrix
NetworkCore.network_from_matrix — Function
network_from_matrix(A::AbstractMatrix; directed::Bool=true, loops::Bool=false,
ignore_eval=nothing, names_eval=nothing,
missing_mask=nothing) -> NetworkCreate a network from an adjacency matrix.
Missing dyads
Masked (unobserved) dyads can be restored in two ways, which differ in whether the dyad's face value survives:
missingentries inAare read back as masked dyads. Because themissingoverwrote the face value in the matrix, the restored dyad has an absent face value. Mask-preserving, face-value-lossy — enough forn_missing_dyads(network_from_matrix(as_matrix(net; missing_value=missing)))to round-trip.missing_mask— aBoolmatrix the size ofA— masks those dyads while reading the face value fromAitself. This is the fully lossless path, and pairs withas_matrix(net; return_mask=true):
net = network(3)
add_edge!(net, 1, 2)
set_missing_dyad!(net, 2, 3)
A, mask = as_matrix(net; return_mask=true)
net2 = network_from_matrix(A; missing_mask=mask, directed=is_directed(net))
n_missing_dyads(net2) # 1Arguments
A::AbstractMatrix: Adjacency matrix (may containmissing)directed::Bool=true: Whether to create a directed networkloops::Bool=false: Whether to allow self-loopsignore_eval: Function to test if a value should be ignored (default: ==(0))names_eval: Optional vertex namesmissing_mask: OptionalBoolmatrix marking masked dyads
Example
A = [0 1 1; 1 0 0; 1 0 0]
net = network_from_matrix(A; directed=false)Edge List to Network
network_from_edgelist
NetworkCore.network_from_edgelist — Function
network_from_edgelist(edges; n::Union{Int,Nothing}=nothing,
directed::Bool=true, loops::Bool=false) -> NetworkCreate a network from an edge list.
Every listed edge ends up in the network or the call throws: an endpoint outside 1:n (an undersized n=, or a mistyped ID) and a self-loop when loops=false are ArgumentErrors naming the offending edge, as R's network(el, matrix.type="edgelist") errors on an illegal edgelist reference — never a silently smaller network. Repeated edges collapse to one (parallel edges are not supported).
Arguments
edges: Edge list as Matrix (n x 2) or Vector of tuplesn::Union{Int,Nothing}: Number of vertices (auto-detected as the largest endpoint if nothing; pass it explicitly to keep trailing isolates)directed::Bool=true: Whether to create a directed networkloops::Bool=false: Whether to allow self-loops
Example
edges = [(1, 2), (2, 3), (3, 1)]
net = network_from_edgelist(edges)DataFrame to Network
network_from_dataframe
NetworkCore.network_from_dataframe — Function
network_from_dataframe(df::DataFrame; source::Symbol=:source, target::Symbol=:target,
directed::Bool=true, loops::Bool=false) -> NetworkCreate a network from a DataFrame with source and target columns. Columns other than source/target become edge attributes.
Requires DataFrames.jl to be loaded (using DataFrames); the method is provided by the NetworkDataFramesExt package extension.
Arguments
df::DataFrame: DataFrame with edge informationsource::Symbol: Column name for source verticestarget::Symbol: Column name for target verticesdirected::Bool: Whether to create a directed networkloops::Bool: Whether to allow self-loops
Example
using NetworkCore, DataFrames
df = DataFrame(source = [1, 2, 3], target = [2, 3, 1], weight = [1.0, 2.0, 1.5])
net = network_from_dataframe(df)
ne(net), get_edge_attribute(net, :weight, 3, 1) # (3, 1.5)Pajek I/O
read_pajek
NetworkCore.read_pajek — Function
read_pajek(filepath::String) -> NetworkRead a network from a Pajek (.net) file.
Pajek Format
*Vertices n
1 "vertex1"
2 "vertex2"
...
*Edges (or *Arcs for directed)
1 2 weight
2 3 weight
...An *Arcs section gives a directed network, *Edges an undirected one; vertex labels are stored as the :vertex_names vertex attribute and edge weights (when present) as the :weight edge attribute — the same names write_pajek reads, so the two round-trip.
Also read: the list sections *Arcslist / *Edgeslist (1 2 3 4 is the three ties 1→2, 1→3, 1→4; no weights), the two-mode header *Vertices n n₁ (a two-mode network with bipartite = n₁), and self-loops (the network is created with loops=true when the file contains one). A tie the network cannot hold — an endpoint outside 1:n, a within-mode pair under a two-mode header — is an ArgumentError, never a silently smaller network; a tie listed twice is kept once (with the last weight), with a warning, because parallel edges are not supported. *Matrix sections are refused with an ArgumentError; other * sections (*Network, *Partition, …) are skipped.
Example
path = tempname() * ".net"
write(path, join(["*Vertices 3", "1 a", "2 b", "3 c", "*Arcs", "1 2 1", "2 3 2"], "\n"))
net = read_pajek(path)
nv(net), ne(net), is_directed(net) # (3, 2, true)
get_edge_attribute(net, :weight, 2, 3) # 2.0write_pajek
NetworkCore.write_pajek — Function
write_pajek(net::Network, filepath::String; vertex_names::Symbol=:vertex_names,
edge_weight::Symbol=:weight)Write a network to a Pajek (.net) file.
Arguments
net::Network: The network to writefilepath::String: Output file pathvertex_names::Symbol: Vertex attribute to use as labelsedge_weight::Symbol: Edge attribute to use as weights
Example
net = network(3; directed=false)
add_edges!(net, [(1, 2), (2, 3)])
set_vertex_attribute!(net, :vertex_names, ["a", "b", "c"])
path = tempname() * ".net"
write_pajek(net, path)
ne(read_pajek(path)) # 2GraphML
write_graphml
NetworkCore.write_graphml — Function
write_graphml(net::Network, filepath::String)Write a network to GraphML format (basic implementation): every vertex and edge attribute becomes a <key>/<data> pair, and edgedefault follows the network's directedness. There is no reader; the file is for igraph, Gephi, NetworkX and the like.
Example
net = network(3)
add_edge!(net, 1, 2)
set_vertex_attribute!(net, :name, ["a", "b", "c"])
path = tempname() * ".graphml"
write_graphml(net, path)
occursin("<graphml", read(path, String)) # trueCSV Edge List
write_edgelist_csv
NetworkCore.write_edgelist_csv — Function
write_edgelist_csv(net::Network, filepath::String; attrs::Vector{Symbol}=Symbol[])Write network as a CSV edge list with columns source,target plus one column per requested edge attribute. Fields containing commas, quotes, or newlines are quoted RFC-4180 style.
Example
net = network(3)
add_edges!(net, [(1, 2), (2, 3)])
set_edge_attribute!(net, :weight, 1, 2, 2.5)
path = tempname() * ".csv"
write_edgelist_csv(net, path; attrs=[:weight])
readlines(path) # ["source,target,weight", "1,2,2.5", "2,3,"]