对于下面的代码,我想在向量(a*b)
中存储每个边的op1
,然后将所有向量存储在列表opp1
中。根据给定的数据:我应该有5个向量op1
,每个向量具有不同的长度(例如:length(op1[1]=3)
,而长度为2
的其余向量如length(op1[2]=2)
)我将有一个列表opp1
包含不同长度的向量。
将值存储在向量中是正常的,但我的问题是在存储这些向量时,结果列表包含向量但长度相同,即opp1
列表包含所有op1
向量的长度3所以从没有地方添加了一个奇怪的值。
library(igraph)
graph<-matrix(c(4,3,4,1,4,2,3,2,3,1),ncol=2,byrow=TRUE)
g<-graph.data.frame(d = graph, directed = FALSE)
v1<-c()
v2<-c()
n1<-list()
n2<-list()
op1<-c()
opp1<-list()
for (edge in 1:length(E(g))){
v1[edge] <- ends(graph = g, es = edge)[1]
v2[edge] <- ends(graph = g, es = edge)[2]
n1[[edge]] <- names(neighbors(g, v1[edge], mode = "all"))
n2[[edge]] <- names(neighbors(g, v2[edge], mode = "all"))
for (neighbor in 1:length(n2[[edge]])){
a<-as.numeric(v2[edge])
b<-as.numeric(n2[[edge]][neighbor])
c<-(a*b)
op1[neighbor]<-c
}
opp1[[edge]]<-op1
}
列表opp1
是:
opp1
[[1]]
[1] 12 3 6
[[2]]
[1] 4 3 6
[[3]]
[1] 8 6 6
[[4]]
[1] 8 6 6
[[5]]
[1] 4 3 6
虽然它应该是:
opp1
[[1]]
[1] 12 3 6
[[2]]
[1] 4 3
[[3]]
[1] 8 6
[[4]]
[1] 8 6
[[5]]
[1] 4 3
是否有任何建议如何修复代码,还有另一种方法以不同的方式执行相同的工作,尤其是在处理大数据时节省时间和内存。 提前谢谢。
答案 0 :(得分:2)
你必须在第一个for循环中初始化lowest
,以便在每个循环中有一个干净的op1
,如下所示:
op1
你的输出:
for (edge in 1:length(E(g))){
op1<-c()
v1[edge] <- ends(graph = g, es = edge)[1]
v2[edge] <- ends(graph = g, es = edge)[2]
n1[[edge]] <- names(neighbors(g, v1[edge], mode = "all"))
n2[[edge]] <- names(neighbors(g, v2[edge], mode = "all"))
for (neighbor in 1:length(n2[[edge]])){
a<-as.numeric(v2[edge])
b<-as.numeric(n2[[edge]][neighbor])
c<-(a*b)
op1[neighbor]<-c
}
opp1[[edge]]<-op1
}
没有for循环更好更快:
opp1
[[1]]
[1] 12 3 6
[[2]]
[1] 4 3
[[3]]
[1] 8 6
[[4]]
[1] 8 6
[[5]]
[1] 4 3