2

我遇到了一个问题。

我有以下风景:

# 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=";"))))

然而,不工作

4

1 回答 1

2

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)"
于 2013-08-08T14:20:09.883 回答