我正在尝试编写一个自定义函数,该函数评估网络中相对于特定顶点属性平衡了多少个三角形。重要的是,属性名称应在函数调用中可自定义。
示例:
# Creating graph
A <- graph(c("a","b",
"a","c",
"c","b",
"d","e",
"e","a",
"d","f",
"f","e",
"g","a",
"g","e"),
directed = FALSE)
V(A)$color <- c("lightblue",
"lightcoral",
"lightcoral",
"lightblue",
"lightblue",
"lightblue",
"lightcoral")
V(A)$shape <- c("circle",
"circle",
"circle",
"square",
"square",
"square",
"square")
我想要一个函数,让我检查A
中的三角形相对于color
,shape
或其他顶点可能具有的任何其他属性是否平衡。 / p>
这是我到目前为止尝试过的:
TriadBalance <- function(network,attribute){
# Getting a List of all closed triangles in the network
TriMat <- matrix(triangles(network), nrow=3)
TriList <- lapply(seq_len(ncol(TriMat)), function(i) TriMat[,i])
# Getting their attribute
AttributeList <- lapply(TriList,function(x){return(V(network)[unlist(x)]$attribute)})
# Checking if the attribute is the same in all triads
Balance <- lapply(AttributeList, function(x){length(unique(unlist(x))) == 1})
# counting the number of balanced triads
NoBalance <- sum(unlist(Balance))
return(NoBalance)
}
此方法中的错误发生在以下行:AttributeList <- lapply(TriList,function(x){return(V(network)[unlist(x)]$attribute)})
,因为$attribute
部分的求值结果不是函数调用中的相应输入。
问题的核心:
attribute = "color"
V(A)[c(1,2,3)]$attribute
V(A)[c(1,2,3)]$color
前两个折点返回NULL,第二个折点正确输出前三个节点的顶点属性。
通过函数调用传递顶点属性名称是否有其他方法?
答案 0 :(得分:2)
我将展示如何将属性值作为一个小函数来获取,但是您可以将代码内联到函数中。要通过属性名称获取属性,只需grep
属性名称即可找出属性的索引,然后通过其索引号访问该属性。
library(igraph)
SelectVAttr = function(graph, aName) {
NamePattern = paste0("^", aName, "$")
Index = grep(NamePattern, names(vertex_attr(graph)))
vertex_attr(A)[[Index]]
}
## Using the example that you provided
SelectVAttr(A, "color")
[1] "lightblue" "lightcoral" "lightcoral" "lightblue" "lightblue"
[6] "lightblue" "lightcoral"
SelectVAttr(A, "shape")
[1] "circle" "circle" "circle" "square" "square" "square" "square"
NamePattern是为了确保您仅获得完全匹配的内容,而不仅仅是部分匹配的内容。