How to construct an edge list from data in R? -
i have data looks this:
+--------+-----------+ | source | targets | +--------+-----------+ | 1 | 3, 4, 5 | | 2 | 1, 3 | | 3 | 6, 10, 11 | +--------+-----------+
where source node in graph data, , targets list of target nodes, i.e. there's connection node 1 3, 4, d 5 nodes. want create edges list, so:
+------+----+ | | | +------+----+ | 1 | 3 | | 1 | 4 | | 1 | 5 | +------+----+
but i'm having trouble getting done in r. best i've been able yet following:
extract_edges <- function(row) { targets <- strsplit(as.character(locke_relations[row, 3]), ", ") df <- data.frame() for(t in targets) { newrow <- data.frame(from=locke_relations[row,1], to=t) df <- rbind(df, newrow) } df } lapply((2:3), extract_edges)
locke_relations
above data more or less in form above, , in code above, processing 2 rows (rows 2 & 3). gets me list containing dataframes more or less corrrect:
[[1]] 1 47678 48378 2 47678 48379 [[2]] 1 47686 47804 2 47686 49326
but want here is:
1 47678 48378 2 47678 48379 3 47686 47804 4 47686 49326
i try find way merge list feel whole approach here off , in r there more efficient way this. know how best way in r?
you can use separate_rows
tidyr
:
tidyr::separate_rows(df, targets) # source target #1 1 3 #2 1 4 #3 1 5 #4 2 1 #5 2 3 #6 3 6 #7 3 10 #8 3 11
Comments
Post a Comment