首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从一组tidygraph对象inR中操作一个tidygraph对象?

如何从一组tidygraph对象inR中操作一个tidygraph对象?
EN

Stack Overflow用户
提问于 2021-09-09 01:18:45
回答 2查看 124关注 0票数 2

如果我有一个tidygraph对象的列表,我想根据某些条件删除列表元素。例如,如果我有一个整洁的图形对象列表,如下所示:

代码语言:javascript
复制
nodes <- data.frame(name = c("Hadley", "David", "Romain", "Julia"))
edges <- data.frame(from = c(1, 1, 1, 2, 3, 3, 4, 4, 4),
                    to = c(2, 3, 4, 1, 1, 2, 1, 2, 3))
nodes_1 <- data.frame(name = c(NA))
edges_1 <- c()

tg <- tbl_graph(nodes = nodes, edges = edges)
tg_1 <- tbl_graph(nodes = nodes_1, edges = edges_1)

myList <- list(tg, tg_1)

查看myList的输出,我们可以看到其中一个tidygraph对象没有与其关联的边,并且names列是NA

代码语言:javascript
复制
> myList
[[1]]
# A tbl_graph: 4 nodes and 9 edges
#
# A directed simple graph with 1 component
#
# Node Data: 4 × 1 (active)
  name  
  <chr> 
1 Hadley
2 David 
3 Romain
4 Julia 
#
# Edge Data: 9 × 2
   from    to
  <int> <int>
1     1     2
2     1     3
3     1     4
# … with 6 more rows

[[2]]
# A tbl_graph: 1 nodes and 0 edges
#
# A rooted tree
#
# Node Data: 1 × 1 (active)
  name 
  <lgl>
1 NA   
#
# Edge Data: 0 × 2
# … with 2 variables: from <int>, to <int>

我想知道是否有一种方法可以遍历列表并检查是否有任何tidygraph对象没有边缘数据或为NA (如上面的示例),并将此对象从列表中删除。

我知道我可以使用myList <- myList[-2]手动删除列表。但是当我的列表中有大量的tidygraph对象时,我正在寻找一个更通用的解决方案?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-09-09 01:37:22

您可以使用返回边缘计数的igraph::gsize()来过滤列表:

代码语言:javascript
复制
library(tidygraph)
library(igraph)

Filter(function(x) gsize(x) > 0, myList)  # Filter(gsize, myList) also works but potentially less safe.

# Or

purrr::discard(myList, ~ gsize(.x) == 0)

[[1]]
# A tbl_graph: 4 nodes and 9 edges
#
# A directed simple graph with 1 component
#
# Node Data: 4 x 1 (active)
  name  
  <chr> 
1 Hadley
2 David 
3 Romain
4 Julia 
#
# Edge Data: 9 x 2
   from    to
  <int> <int>
1     1     2
2     1     3
3     1     4
# ... with 6 more rows
票数 1
EN

Stack Overflow用户

发布于 2021-09-09 01:31:58

我们可能会做

代码语言:javascript
复制
library(purrr)
library(tibble)
library(dplyr)
keep(myList, ~ .x %>% 
              as_tibble %>%
              pull(name) %>%
              is.na %>% 
              `!` %>% 
               any)

-output

代码语言:javascript
复制
[[1]]
# A tbl_graph: 4 nodes and 9 edges
#
# A directed simple graph with 1 component
#
# Node Data: 4 x 1 (active)
  name  
  <chr> 
1 Hadley
2 David 
3 Romain
4 Julia 
#
# Edge Data: 9 x 2
   from    to
  <int> <int>
1     1     2
2     1     3
3     1     4
# … with 6 more rows
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69111178

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档