r - How to create full path out of parent/child pairs
问题描述
I have a data frame with a column which holds parent/child pairs except for the first row. It looks like this:
test<-c("0", "0/00", "00/000", "00/001", "001/001.01", "001.01/001.012", "001/001.0601", "001/001.089", "001/001.09", "001/001.1")
testdf <- data.frame(test)
test
1 0
2 0/00
3 00/000
4 00/001
5 001/001.01
6 001.01/001.012
7 001/001.0601
8 001/001.089
9 001/001.09
10 001/001.1
The first row consists of the root "0". The desired output would look like this:
test
1 0
2 0/00
3 0/00/000
4 0/00/001
5 0/00/001/001.01
6 0/00/001/001.01/001.012
7 0/00/001/001.0601
8 0/00/001/001.089
9 0/00/001/001.09
10 0/00/001/001.1
I'd like to visualize this data as a tree using igraph. Thanks!
解决方案
基本上,您有一个边缘列表,因此您只需将数据按摩成可供graph_from_edgelist
. 这只是一个小字符串操作。
library(igraph)
Pairs = as.character(testdf$test[grep("/", testdf$test)])
EL = matrix(unlist(strsplit(Pairs, "/")), ncol=2, byrow=TRUE)
G = graph_from_edgelist(EL)
LO = layout_as_tree(G, root="0")
plot(G, layout=LO)
要获取路径的文本版本,您可以使用:
sapply(shortest_paths(G, "0", V(G))$vpath,
function(x) paste(x$name, collapse="/"))
[1] "0" "0/00"
[3] "0/00/000" "0/00/001"
[5] "0/00/001/001.01" "0/00/001/001.01/001.012"
[7] "0/00/001/001.0601" "0/00/001/001.089"
[9] "0/00/001/001.09" "0/00/001/001.1"
推荐阅读
- mysql - MySQL 查询以了解计划合规性
- r - 如何在 R 中使用 corrplot() 仅显示前 10 个最强的相关变量?
- javascript - 如何使用谷歌应用脚本在javascript中传递数组
- javascript - 链接或组合多个“修补程序”的好方法?
- python - tensorflow 首次运行问题
- autohotkey - 如何调整最初为 1920p 编写的 Autohotkey 脚本,以便它们可以在 4k 显示器上正确缩放?
- python - 使用 numpy 映射具有多个输入的函数
- android - 哪一个是 Kotlin 中 hashMapOf 的关键?
- javascript - 错误类型错误:无法读取未定义的属性“打开”
- sql - SQL 强制转换