如何在R中的一个变量中存储属性值列表的所有值?

时间:2017-11-02 23:58:48

标签: r igraph

我有这样的代码:

library(igraph)
g <- make_empty_graph (2) %>%
  set_vertex_attr("a", value = 1) %>%
  add_vertices(2, color = 2, "a" = 2) %>%
  add_vertices(2, color = 4, "a" = 3) %>%
  add_edges(c(1,2, 2,1, 1,5, 5,1, 1,4 ,4,1)) %>%
  set_vertex_attr("xyz", value = 3)
plot(g)


i <- 1
prev_value <- FALSE

repeat {
  print(V(g)$a)
  print(mean(V(g)$a == 1))
  print(i)

  V(g)$xyz = sapply(V(g), function(x) {
    NeighborList = neighbors(g, x)
    length(NeighborList[NeighborList$a == 2])
  })
  V(g)$a[V(g)$xyz == 1] = 2
  prev_value <- V(g)$a[i]
  i <- i + 1


  if (V(g)$a[i] == prev_value) {
    break
  }

}

但是,当我运行此代码时,prev_value仅存储V(g)$ a的第一个值。我该如何解决这个问题?我跑的时候

print(prev_value)

我得到的输出是“1”,而我真正想要的输出是'“1”“1”“0”“0”“0”“0”“0”“0”'(初始值为V(G)$ A)

1 个答案:

答案 0 :(得分:0)

为prev_value添加索引,使其像向量

一样构建
i <- 1
prev_value <- FALSE

repeat {
  print(V(g)$a)
  print(mean(V(g)$a == 1))
  print(i)

  V(g)$xyz = sapply(V(g), function(x) {
    NeighborList = neighbors(g, x)
    length(NeighborList[NeighborList$a == 2])
  })

  if (V(g)$a[i] == prev_value[i-1]) {
    break
  }

  V(g)$a[V(g)$xyz == 1] = 2
  prev_value[i] <- V(g)$a[i]

  i <- i + 1
}