我正在使用networkD3
软件包,但是无法使用我的数据建立某些子网。
我有一个以此方式制作的数据集({MisNodes
和MisLinks
由程序包本身提供):
library(networkD3)
data("MisNodes")
head(MisNodes)
# name group size
# 1 Myriel 1 15
# 2 Napoleon 1 20
# 3 Mlle.Baptistine 1 23
# 4 Mme.Magloire 1 30
# 5 CountessdeLo 1 11
# 6 Geborand 1 9
data("MisLinks")
head(MisLinks)
# source target value
# 1 1 0 1
# 2 2 0 8
# 3 3 0 10
# 4 3 2 6
# 5 4 0 1
# 6 5 0 1
整个网络是这样的:
forceNetwork(
Links = MisLinks, Nodes = MisNodes,
Source = "source", Target = "target",
Value = "value", NodeID = "name",
Group = "group", opacity = 1)
现在,我想选择一个组,仅查看该组的节点,以及以该组中的节点作为来源的链接:
所以我尝试了这个:
# here the group
k <-c(1)
# add id, to subset well
MisNodes$id <- rownames(MisNodes)
# select the desired nodes
nodes <- (MisNodes[MisNodes$group %in% k,])
# select the links that have as source the desired nodes
links <- (MisLinks[rownames(MisLinks) %in% nodes$id,])
# rownames from 0
rownames(nodes) <- 1:nrow(nodes)-1
# indexing from 0 to max
links$source_ <-match(links$source, sort(unique(links$source)))-1
links$target_ <-match(links$target, sort(unique(links$target)))-1
但是结果不正确,因为应该将单独的点链接到中心节点。
查看链接:
links
source target value source_ target_
1 1 0 1 0 0
2 2 0 8 1 0
3 3 0 10 2 0
4 3 2 6 2 1
5 4 0 1 3 0
6 5 0 1 4 0
7 6 0 1 5 0
8 7 0 1 6 0
9 8 0 2 7 0
10 9 0 1 8 0
似乎源从1开始,但目标从0开始,但除去-1,它适用于第一组,但不适用于其他组。同样,使用k <-c(1,2,3,4,5,6,7,8,9,10)
的总数也不正确。如何使网络正确响应数据的子集?
答案 0 :(得分:3)
节点ID使用基于0的索引,您还应删除目标节点不在组中的链接,否则,您可能具有指向节点数据中不存在的目标节点的链接(不会不会发生在第1组中,但发生在其他组中。
library(networkD3)
data("MisNodes")
data("MisLinks")
group <- 1
nodes <- MisNodes
# record the original id (0-based index of the node in the data)
nodes$original_id <- 0:(nrow(MisNodes) - 1)
# trim the nodes to only those in the desired group
nodes <- nodes[nodes$group == group, ]
links <- MisLinks
# trim the links to only those that have a source and target node
# within the desired group
links <- links[links$source %in% nodes$original_id &
links$target %in% nodes$original_id, ]
# match the node ids in the links data to the original id of the nodes
# and reset it to the current 0-based index of the nodes
links$source <- match(links$source, nodes$original_id) - 1
links$target <- match(links$target, nodes$original_id) - 1
forceNetwork(links, nodes,
Source = "source", Target = "target",
Value = "value", NodeID = "name",
Group = "group", opacity = 1)