【问题标题】:How to return unique sub-elements of igraph list in R如何在R中返回igraph列表的唯一子元素
【发布时间】:2019-11-11 05:41:25
【问题描述】:

我有一个来自igraph 对象的列表walks

> walks
[[1]]
+ 3/10 vertices, named, from d1edbf2:
[1] C O D

[[2]]
+ 3/10 vertices, named, from d1edbf2:
[1] C O J

[[3]]
+ 3/10 vertices, named, from d1edbf2:
[1] C O N

[[4]]
+ 3/10 vertices, named, from d1edbf2:
[1] C O N

我需要返回列表的唯一子元素。 预期结果是:

[[1]]
[1] C O D

[[2]]
[1] C O J

[[3]]
[1] C O N

我尝试在玩具示例列表中使用unique() 函数

list1 = list(c("C", "O", "D"), c("C", "O", "J"), c("C", "O", "N"), c("C", "O", "N"))
unique(list1)

而且我已经得到了预期的结果。

问题。如何获取来自igraph对象的列表的结果?

编辑。

> dput(walks)
list(structure(c(1L, 7L, 2L), .Names = c("C", "O", "D"), env = <weak reference>, graph = "d1edbf24-043a-11ea-aa53-d7a9b9f5ae37", class = "igraph.vs"), 
    structure(c(1L, 7L, 4L), .Names = c("C", "O", "J"), class = "igraph.vs", env = <weak reference>, graph = "d1edbf24-043a-11ea-aa53-d7a9b9f5ae37"), 
    structure(c(1L, 7L, 6L), .Names = c("C", "O", "N"), env = <weak reference>, graph = "d1edbf24-043a-11ea-aa53-d7a9b9f5ae37", class = "igraph.vs"), 
    structure(c(1L, 7L, 6L), .Names = c("C", "O", "N"), env = <weak reference>, graph = "d1edbf24-043a-11ea-aa53-d7a9b9f5ae37", class = "igraph.vs"))

我看到的简写形式:

> dput(walks, control = NULL)
list(c(1, 7, 2), c(1, 7, 4), c(1, 7, 6), c(1, 7, 6))

【问题讨论】:

  • 你能分享dput(walks)吗?
  • @RonakShah,我添加了 dput() 函数的输出。

标签: r list unique igraph


【解决方案1】:

unique 函数是正确的选择,在这种情况下它不起作用,因为列表中的元素有一个类“igraph”。您需要先提取名称,然后应用唯一的。

你的输入中有一些奇怪的“env”,所以我模拟了下面的一些数据来说明它:

library(igraph)
set.seed(111)
g <- make_ring(9, directed = TRUE) %u%
  make_star(10, center = 10) + edge(10, 1)
g <- set.vertex.attribute(g, "name", value=letters[1:10])

result = lapply(1:5,function(i)random_walk(g, start = 1, steps = 3))

你会得到与你的例子类似的东西:

> result
[[1]]
+ 3/10 vertices, named, from 0105e1a:
[1] a b c

[[2]]
+ 3/10 vertices, named, from 0105e1a:
[1] a b c

[[3]]
+ 3/10 vertices, named, from 0105e1a:
[1] a j a

[[4]]
+ 3/10 vertices, named, from 0105e1a:
[1] a j a

[[5]]
+ 3/10 vertices, named, from 0105e1a:
[1] a j a

> class(result[[1]])
[1] "igraph.vs"

您可以检查两个不同的输出:

# does not work for you
unique(walks)
# this works
unique(lapply(walks,names))
> unique(lapply(walks,names))
[[1]]
[1] "a" "j" "a"

[[2]]
[1] "a" "b" "c"

[[3]]
[1] "a" "b" "j"

【讨论】:

  • 谢谢,代码对我有用。我的 dput 中出现一些奇怪的“env”的原因是什么?你有什么想法吗?
  • 嗨@Nick 很高兴它对你有用。至于“env”,如果你用我的例子,做str(g),你可以看到attr(, "env")= and attr(, "graph")=字符“841251eb-4389-4933-b79a-8740794a0e3f”。这将与您的不同,所以我认为这是 igraph 使用的一些设置...不太确定。
猜你喜欢
  • 1970-01-01
  • 2020-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-30
  • 1970-01-01
  • 2016-09-26
  • 1970-01-01
相关资源
最近更新 更多