2017-10-16 70 views
-7

我得到這個循環重寫循環:R:使用sapply

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是,我使用的igraph封裝的GML曲線圖。我想將其重寫爲函數,使用sapply()將函數應用於E(g)以獲取作爲輸出的向量。

+0

有無數如何在這個網站上編寫'lapply' /'sapply'循環的例子。我們確實不需要另一個問題/(自己)答案對。 – Roland

回答

-2
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) 
+0

請詳細解釋。 – OmG