从r中的整组列表中提取元素

Extracting elements from whole set of list in r

下面的代码是我的 R 脚本。我想从我的 r 脚本的结果列表中获取 $r[[1]] 和 $r1:loop_results。下面是 loop_results 的第一个元素的一部分看起来如何的示例。我想要一个仅显示最短路径序列的列表,例如 1 和 1 2,以及一个仅包含顶点序列的列表,例如 A 和 A B。

[[1]]
[[1]][[1]]
[[1]][[1]]$r
[[1]][[1]]$r[[1]]
[1] 1


[[1]][[1]]$r1
Vertex sequence:
[1] "A"


[[1]][[2]]
[[1]][[2]]$r
[[1]][[2]]$r[[1]]
[1] 1 2


[[1]][[2]]$r1
Vertex sequence:
[1] "A" "B"

这是我的 R 脚本

library(igraph)
  g <- graph.ring(5) # the graph
  V(g)$name <- LETTERS[1:5] # Vertex names
  # Define functions:
  val=function(g,i,j) { r=get.shortest.paths(g, i,j ,mode = "out"); return(r) } 
  val_all=function(r) { r1 <- V(g)[r$vpath[[1]]]; return(r1) }

  loop_results <- list()
  for (i in 1:5) {
    loop_results[i] <- list(NULL)
    for(j in 1:5) { 

      r=val(g ,i, j)
      print(r[[1]]) 
      r1 = val_all(r)
      print(r1)
      loop_results[[i]][[j]] <- list(r=r[[1]], r1=r1)
    }
  }
  loop_results

我从 dput(loop_results) 得到以下输出:

  list(list(structure(list(r = list(1), r1 = structure(1, 
  class ="igraph.vs", env = <environment>)), .Names = c("r", 
  "r1")), structure(list(r = list(c(1, 2)), 
   r1 = structure(c(1, 2), 
   class = "igraph.vs", env = <environment>)), .Names = c("r", "r1")),
   structure(list(r = list(c(1, 2, 3)), r1 = structure(c(1, 2, 3), 
   class = "igraph.vs", env = <environment>)), .Names = c("r", "r1")),
    structure(list(r = list(c(1, 5, 4)), r1 = structure(c(1, 5, 4)       class = "igraph.vs",env = <environment>)), 
    .Names = c("r", "r1")), structure(list(r = list(c(1, 5)), r1 =      structure(c(1, 5),class = "igraph.vs", env = <environment>)), .Names = c("r", "r1"))) 

在这种形式下,其余4个字母也各有千秋。 get.shortest.path 函数中的 R 只会将 return 最短路径序列作为数字。如果我们有带字符串的顶点,那么我们用我在 r 脚本中使用 val_all 函数的最短路径结果打印出顶点序列名称。

我的主要目标是找到包含具有中间节点的最短路径序列的列表。就像在我的示例中我想找到节点 "A" 和 "C" 之间的最短路径,结果将是 A B C。然后,我只想打印中间节点 "B" 而不是"A" 和 "C",它们是我寻找最短路径的起点和终点。为此,我正在考虑在 r 中使用 setdiff() 函数,并且对于这个函数我需要传递一个列表,这就是为什么我想要我之前提到的列表的原因。

如果您想根据数据是与 r 还是 r1 关联,将现有列表拆分为两个列表,您可以使用嵌套的 lapply 调用来完成此操作:

r:

lapply(seq_along(loop_results), 
    function(x) lapply(seq_along(loop_results[[x]]), 
         function(y) loop_results[[x]][[y]][["r"]]))

r1:

lapply(seq_along(loop_results), 
    function(x) lapply(seq_along(loop_results[[x]]), 
        function(y) loop_results[[x]][[y]][["r1"]]))