我正在尝试使用 in 中的igraph表来计算一些网络度量。一开始,我读取我的数据,而不是对其进行转换,并最终将其转化为邻接矩阵形式。然后计算这个数据集的度值。
我想把我的代码放在一个循环中,这样我就不需要手动更改条件--重新读取数据--然后再次运行代码。但我运气不好。"r“条件可以是"1”或"2",而"g“条件是从"1”到"21“的数字。
到目前为止,我的代码如下所示:
p1 <- read.csv("matrix.csv")
p <- p1[p1$r=="1" & p1$g == "1",]
rownames(p) <- paste("id", p$id, sep=".")
p <- t(p[,-(1:3)])
p <- data.frame(p)
rr <- apply(p, 2, as.character)
m<-matrix(nrow=ncol(rr),ncol=ncol(rr))
for(col in 1:ncol(rr)){
matches<-rr[,col]==rr
match.counts<-colSums(matches)
match.counts[col]<-0
m[,col]<-match.counts
}
n<-graph.adjacency(m)
d<-degree(n, v=V(n))“p1”的前几行:
1> p1
id g r X1 X2 X3 X4
1 1 1 1 1324;1256 1324;1256 752;1268 1892;1236
2 2 1 2 324;988 324;988 324;988 324;988
3 3 1 1 1312;1652 1312;1652 1828;608 712;656
4 4 1 2 324;988 324;988 324;988 324;988 ...我知道我的代码很难看..。我没有以前的编程经验,但我渴望学习,所以我欢迎任何类型的建议或建议。
提前感谢!
发布于 2014-07-22 13:38:10
这里我假设前3列是标识符,下面的任何列都以V1;V2格式描述图形,其中V1和V2是顶点ids。
仅取一小部分数据框架,以下是我想出的。我不认为您需要创建一个邻接矩阵,因为您可以创建一个边缘列表。
require(igraph)
p1 <- read.csv(textConnection(
"id,g,r,X1,X2,X3,X4
1,1,1,1324;1256,1324;1256,752;1268,1892;1236
2,1,2,324;988,324;988,324;988,324;988
3,1,1,1312;1652,1312;1652,1828;608,712;656
4,1,2,324;988,324;988,324;988,324;988"))若要对r和g的值执行此操作,请执行以下操作:
p <- p1[p1$r=="1" & p1$g == "1",] ## limit to only rows where r and g are 1
myEdges <- p[,-(1:3)] ## assuming edges are defined in all columns after the first 3
dat <- apply(myEdges, 1, function(strings) unlist(strsplit(strings, ';', fixed=TRUE)))
myGraph <- graph.data.frame(dat, directed=FALSE) # can change to directed by setting directed = TRUE
plot(myGraph) # see what the graph looks like, don't try if graph is large!
degree(myGraph)
# 1324 1256 752 1268 1892 1236 1312 1652 1828 608 712 656
# 2 2 1 1 1 1 2 2 1 1 1 1要回答关于对r和g的不同组合自动处理过程的评论,可以使用类似于嵌套for循环的方法(虽然效率不高,但可能会根据大小而解决问题)。
rVals <- 1:2
gVals <- 1:21
myGraphList <- rep( list(vector(mode = "list", length = length(gVals) )), length(rVals))
for(r in rVals) {
for(g in gVals) {
p <- p1[p1$r == r & p1$g == g,] ## limit to only certain values of r and g
myEdges <- p[,-(1:3)] ## assuming edges are defined in all columns after the first 3
if(nrow(myEdges) > 0) { ## Only need to create a graph if there are edges present
dat <- apply(myEdges, 1, function(strings) unlist(strsplit(strings, ';', fixed=TRUE)))
myGraphList[[r]][[g]] <- graph.data.frame(dat, directed=FALSE)
}
}
}
## Only 2 elements with an igraph object in this small example:
degree(myGraphList[[1]][[1]]) # when r == 1, g == 1
# 1324 1256 752 1268 1892 1236 1312 1652 1828 608 712 656
# 2 2 1 1 1 1 2 2 1 1 1 1
degree(myGraphList[[2]][[1]]) # when r == 2, g == 1
# 324 988
# 8 8 https://stackoverflow.com/questions/24885922
复制相似问题