0

I would like to learn how to code more efficiently using apply, sapply or lapply. While I understand the basics of it, I am yet lacking intuition. Specifically, I would like to use apply on a graph object. Is it possible to implement the example below with one of these functions and how could it be done? Any more efficient solution is welcome as the graph I am interested has more than 2 Mio. nodes, each having one edge.

# data
g <- make_graph(c(1, 2, 2, 3, 3, 4, 5, 6), directed = T)

# loop 
for(i in 1:length(V(g))){
  neigbours[[i]] <- adjacent_vertices(g, v= c(i), mode = "in")
} 
S Front
  • 333
  • 1
  • 8

1 Answers1

2

lapply is not necessarily more efficient. But you can improve efficiency by creating the object neigbours first, instead of extending it in each for loop iteration, forcing calls to R's memory management routins.

neigbours <- vector("list", length = length(V(g)))
for(i in 1:length(V(g))){
  neigbours[[i]] <- adjacent_vertices(g, v= c(i), mode = "in")
} 

neib2 <- lapply(seq_along(V(g)), function(i){
  adjacent_vertices(g, v = i, mode = "in")
})
all.equal(neigbours, neib2)
# [1] TRUE
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66