我遇到了一个问题。
我有以下风景:
# 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/