簡體   English   中英

R:使用 sapply 重寫循環

[英]R: rewrite loop using 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是一個 gml 圖,我使用的是 igraph 包。 我想將其重寫為函數,使用sapply()將該函數應用於E(g)以獲取向量作為輸出。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM