[英]function to count changes in a network (changes in node attributes)
I would like to count the number of color changes in a.network using a function.我想使用 function 计算 a.network 中颜色变化的次数。
A change would be "red"
to "green"
(from a
to b
in the example)变化将是"red"
到"green"
(示例中从a
到b
)
Overlaps (eg, "green"
to "green"
and "orange"
, from c
to c1
in the example) should not count as a change.重叠(例如, "green"
到"green"
和"orange"
,在示例中从c
到c1
)不应算作更改。
Example data:示例数据:
library(tidyverse)
network <- tibble(
from=c("a","b","c","c"),
to= c("b","c","c1","c2"))
colors <- list(
a=list("red"),
b=list("red"),
c=list("green"),
c1=list("green","orange"),
c2=list("blue","black")
)
The correct output of the function would be 2 (from b
to c
and c
to c2
) in this example.在此示例中,function 的正确 output 将是 2(从b
到c
和c
到c2
)。
This can be vectorized:这可以被矢量化:
# change inner lists in 'colors' to vectors
colors <- lapply(colors, unlist)
count_color_changes <- function(network, colors) {
# list of lists of 'from' and to 'colors'
col.ft <- lapply(network, \(x) colors[x])
# common colors
col.com <- mapply(intersect, col.ft$from, col.ft$to)
# number of transitions where no common color was found
sum(sapply(col.com, length) == 0)
}
count_color_changes(network, colors)
# 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.