I have a network and would like to count cycles of size 4 (paths of length four starting and ending at the same node) and paths of size 3 starting from a node, then tabulate them in a dataset by node.
g <- read.table(text= "supplier buyer
a b
b c
c d
c e
a e
e f
b f",header=TRUE)
g <- graph.data.frame(g, directed=F)
adjacency <- as.matrix(as_adjacency_matrix(g))
I have referred to this post for counting cycles, but it counts cycles for the entire graph, not by node.
I have also read the documentation for kpath.census and kcycle.census. However, these only allow for specification of a maximum length (length <=3, rather than ==3). I'm also not fully understanding the output:
library(sna)
node_path<-sna::kpath.census(adjacency, maxlen = 3, mode = "graph",
tabulate.by.vertex = TRUE, dyadic.tabulation = "sum")
node_kcycle <- sna::kcycle.census(adjacency, maxlen = 4, mode = "graph", tabulate.by.vertex = TRUE, cycle.comembership = "sum")
> node_path$path.count
Agg a b c e f d
1 14 4 6 6 6 4 2
2 22 10 14 14 14 10 4
3 32 20 28 24 28 20 8
> node_kcycle$cycle.count
Agg a b c e f d
2 0 0 0 0 0 0 0
3 0 0 0 0 0 0 0
4 3 2 3 2 3 2 0
I plotted the network below, and by my count, node a should have 4 cycles of length 4, and 6 paths of length 3. But the output from node_kcycle$cycle.count and node_path$path.count provide different numbers.
Is there a better way to count the cycles of size 4 and length of 3 for each node? I'd like to produce an output such that:
cycles4 path3
a 4 6
b
c ....
d
e
f
EDIT: I've figured out my confusion with the kpath.census output: it counts all paths including that node, not starting from that node, as I'd wanted. Still not sure how to count the paths starting from a node, though
EDIT2: This function all_simple_paths(g, from = V(g)) counts the simple paths, and I'm thinking I would try to extract paths of 3 from this function. Still struggling on finding the cycles of size 4.
