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.
CodePudding user response:
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
CodePudding user response:
Here's how you can create a function that counts the number of color changes in a network:
count_color_changes <- function(network, colors) {
# Initialize a counter to 0
counter <- 0
# Iterate over the rows in the network
for (i in 1:nrow(network)) {
# Get the 'from' and 'to' nodes for the current row
from <- network[i, "from"]
to <- network[i, "to"]
# Get the list of colors for the 'from' and 'to' nodes
from_colors <- colors[from]
to_colors <- colors[to]
# Check if there is at least one color that is present in the list
# of colors for both the 'from' and 'to' nodes
common_colors <- intersect(from_colors, to_colors)
# If there are no common colors, then it means that there is a
# color change from the 'from' node to the 'to' node
if (length(common_colors) == 0) {
# Increment the counter
counter <- counter 1
}
}
# Return the counter
return(counter)
}
You can then use this function as follows:
# Count the number of color changes in the network
count_color_changes(network, colors)
# Output: 1
This function first initializes a counter to 0. It then iterates over the rows in the `network