R:使用sapply重写循环
我得到了这个循环:R:使用sapply重写循环,r,R,我得到了这个循环: for(i in E(g)){ a = ends(g, i)[1] b = ends(g, i)[2] source_neighbors = neighbors(g, a) target_neighbors = neighbors(g, b) num_overlap_neighbors = length(intersection(source_neighbors, target_neighbors)) print(num_ove
for(i in E(g)){
a = ends(g, i)[1]
b = ends(g, i)[2]
source_neighbors = neighbors(g, a)
target_neighbors = neighbors(g, b)
num_overlap_neighbors = length(intersection(source_neighbors, target_neighbors))
print(num_overlap_neighbors)
}
g
是一个gml图,我使用的是igraph包。我想将其重写为一个函数,使用sapply()
将该函数应用于E(g)
以获得向量作为输出 请进一步解释。在这个网站上有无数关于如何编写lappy
/sapply
循环的例子。我们真的不需要另一个问题/(自我)答案对。
results=sapply(E(g), function(i){
a = ends(g, i)[1]
b = ends(g, i)[2]
source_neighbors = neighbors(g, a)
target_neighbors = neighbors(g, b)
num_overlap_neighbors = length(intersection(source_neighbors, target_neighbors))
return(num_overlap_neighbors)
})
print(results)