【问题标题】:function to count changes in a network计算网络变化的函数
【发布时间】:2022-12-04 20:25:15
【问题描述】:

我想使用函数计算网络中颜色变化的次数。

更改将是 "red""green"(示例中从 ab

重叠(例如,"green""green""orange",示例中从cc1)不应算作更改。

示例数据:

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")
)

在此示例中,函数的正确输出为 1(从 cc2)。

【问题讨论】:

    标签: r networking


    【解决方案1】:

    下面介绍了如何创建一个函数来计算网络中颜色变化的次数:

    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)
    }
    

    然后,您可以按如下方式使用此功能:

    # Count the number of color changes in the network
    count_color_changes(network, colors)
    # Output: 1
    

    此函数首先将计数器初始化为 0。然后遍历“网络”中的行

    【讨论】:

      猜你喜欢
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-01
      • 2016-09-26
      • 2011-05-03
      • 1970-01-01
      相关资源
      最近更新 更多