Reputation: 347
I have the following network:
edges <- data.frame(from=c('a','1','2','b'), to=c('1','2','3','4'))
edges
from to
1 a 1
2 1 2
3 2 3
4 b 4
And want to identify the neighborhood of "to" nodes in the following way:
1 a NA NA
2 1 a NA
3 2 1 a
4 b NA NA
Ideally I would get only
3 2 1 a
4 b NA NA
because I am only interested in getting the full path from 'a' to '3' and '4' to 'b'.
Using the ego() function from the igraph package I get a list with this information but I have not managed to convert it into a dataframe in the form above:
test <- ego(graph,4,edges[,2], "in")
test
[[1]]
+ 1/6 vertex, named:
[1] a
[[2]]
+ 2/6 vertices, named:
[1] 1 a
[[3]]
+ 3/6 vertices, named:
[1] 2 1 a
[[4]]
+ 1/6 vertex, named:
[1] b
Here are my unsuccessful trials:
require(plyr)
> data.frame(ldply(test, rbind))
a X1 X2 b
1 1 NA NA NA
2 1 2 NA NA
3 1 2 3 NA
4 NA NA NA 4
data.frame(t(unlist(test)))
a X1 a.1 X2 X1.1 a.2 b
1 1 2 1 3 2 1 4
Upvotes: 1
Views: 452
Reputation: 23099
We could use rbind.fill
too:
library(plyr)
rbind.fill(lapply(test, function(x)as.data.frame(t(names(x)))))
# V1 V2 V3
#1 a <NA> <NA>
#2 1 a <NA>
#3 2 1 a
#4 b <NA> <NA>
Upvotes: 2
Reputation: 347
Ok, I've found a way of doing it, but I am not sure if it is the most efficient.
neighbors <- lapply(1:length(test), function(x) names(test[[x]]))
require(plyr)
data.frame(edges$to,ldply(neighbors, rbind))
edges.to X1 X2 X3
1 1 a <NA> <NA>
2 2 1 a <NA>
3 3 2 1 a
4 4 b <NA> <NA>
Upvotes: 0