【问题标题】:R: rewrite loop using sapplyR:使用 sapply 重写循环
【发布时间】:2018-03-27 14:03:30
【问题描述】:

我得到了这个循环:

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) 以获得一个向量作为输出。

【问题讨论】:

  • 在这个网站上有无数关于如何编写lapply/sapply循环的例子。我们真的不需要另一个问题/(自我)答案对。

标签: r


【解决方案1】:
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)

【讨论】:

  • 请解释更多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-13
  • 1970-01-01
  • 1970-01-01
  • 2020-05-03
  • 1970-01-01
  • 2020-04-26
相关资源
最近更新 更多