r - 契约(Contract)顶点图并组合属性

标签 r igraph

我遇到了一个问题。

我有以下风景:

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

但是,不行

最佳答案

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

关于r - 契约(Contract)顶点图并组合属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18127268/

相关文章:

r - 每个公司每个月的最后观察 (R)

r - 如何在 R 中找到箱线图的上限和下限?

python - 生成所有可能的三连通图

R igraph 弯曲边缘

python igraph : nodes and edges color according to a number associated to the node

r - 如何在 R 中模拟具有同配性或同质性的图?

r - 使用ggmap创建 map 和持久错误R

从 R 包描述中读取 Authors@R 字段作为向量

r - 创建具有 3 种颜色的线段的交互线?

r - 我如何旋转更宽并按两列计算一对的出现?