首页 > 解决方案 > R:如何使networkD3网络对数据的子集做出反应

问题描述

我正在使用该networkD3软件包,但无法使用我的数据创建一些子网络。

我有一个以这种方式制作的数据集(MisNodesMisLinks包本身提供):

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)也不正确。如何使网络正确响应数据子集?

标签: rhtmlwidgetsnetworkd3

解决方案


节点 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)

在此处输入图像描述


推荐阅读