【问题标题】:Contract vertices the graph and combine attributes契约顶点图并组合属性
【发布时间】:2013-08-08 22:21:15
【问题描述】:

我遇到了一个问题。

我有以下风景:

# Create a graph
g1 <- graph.full(5)
V(g1)$name <- letters[1:vcount(g1)]
V(g)
Vertex sequence:
[1] "a" "b" "c" "d" "e"

# Contract vertex "a" and "b"
vec = c(1,1,2,3,4)
contract_1 <- contract.vertices(g1, vec, vertex.attr.comb=toString)
V(contract_1)
Vertex sequence:
[1] "a, b" "c" "d" "e"  

# Contract vertex "a, b" and "c"
vec = c(1,1,2,3)
contract_2 <- contract.vertices(contract_1, vec, vertex.attr.comb=toString)
V(contract_2)
Vertex sequence:
[1] "a, b, c" "d" "e"

依此类推...(合约“a,b,c”和“d”,创建顶点“a,b,c,d”)

我需要区分上一层的顶点。

例如:

通过收缩顶点“a,b​​​”和“c”,我需要使用额外的标记作为“|”或者 ”;”。在这种情况下,结果将是 "a, b | c" 或 "a, b- c" 或 "a, b; c"。

通过收缩顶点“a, b, c”和“d”,结果将是“a, b, c | d”或“a, b, c; d”

我尝试了一些东西...

例如:

g <- contract.vertices(g, matching, 
  vertex.attr.comb=list(name=function(x) paste(toString(x,"",sep=";"))))

但是不行

【问题讨论】:

    标签: r igraph


    【解决方案1】:

    paste 也有一个 collapse 参数:

    contract.vertices(
      contract_1, 
      c(1,1,2,3), 
      vertex.attr.comb = list( name = function(x) paste(x, collapse=";") )
    )
    

    您也可以使用嵌套括号:

    library(igraph)
    g <- list()
    k <- 5
    g[[1]] <- graph.full(k)
    V(g[[1]])$name <- letters[1:vcount(g1)]
    for(i in 2:k) { 
      g[[i]] <- contract.vertices(
        g[[i-1]],
        c(1,1,2:k)[1:(k-i+2)],
        vertex.attr.comb = list( name = function(x) 
          if( length(x) > 1 ) paste0( "(", paste0(x,collapse=","), ")" ) else x
        )
      )
    }
    lapply(g, V)
    # [[1]]
    # Vertex sequence:
    # [1] "a" "b" "c" "d" "e"
    # [[2]]
    # Vertex sequence:
    # [1] "(a,b)" "c"     "d"     "e"    
    # [[3]]
    # Vertex sequence:
    # [1] "((a,b),c)" "d"         "e"        
    # [[4]]
    # Vertex sequence:
    # [1] "(((a,b),c),d)" "e"            
    # [[5]]
    # Vertex sequence:
    # [1] "((((a,b),c),d),e)"
    

    【讨论】:

    • 完美。这是我需要的。但是,有一个疑问:如何在结果中导航?换句话说,如何解压缩一层。例如:给定"((((a,b),c),d),e)" 得到"((a,b),c),d)""e"。我会尝试使用正则表达式。
    • 是的,你可以使用正则表达式,例如strsplit( gsub( "\\((.*),([^,]*)\\)", "\\1;\\2", "((((a,b),c),d),e)"), ";" )[[1]]
    猜你喜欢
    • 2017-12-19
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多