ava
ava

Reputation: 996

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.

A change would be "red" to "green" (from a to b in the example)

Overlaps (e.g., "green" to "green" and "orange", from c to c1 in the example) should not count as a change.

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.

Upvotes: 0

Views: 66

Answers (1)

Robert Hacken
Robert Hacken

Reputation: 4725

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

Upvotes: 1

Related Questions