1

我已经使用该d3r包将igraph对象转换为 JSON 格式,如下所示:

# create small world network    
net <- sample_smallworld(size = 8, dim = 1, nei = 1, p = 0.33) 

# convert to json with directional edges   
data_json <- d3_igraph(as.directed(net)) 

这给了我以下输出:

> data_json
{"nodes":[{"id":"0"},{"id":"1"},{"id":"2"},{"id":"3"},{"id":"4"},{"id":"5"},{"id":"6"},{"id":"7"}],"links":[{"source":"0","target":"1"},{"source":"1","target":"6"},{"source":"2","target":"3"},{"source":"3","target":"4"},{"source":"0","target":"4"},{"source":"3","target":"5"},{"source":"6","target":"7"},{"source":"0","target":"7"},{"source":"1","target":"0"},{"source":"6","target":"1"},{"source":"3","target":"2"},{"source":"4","target":"3"},{"source":"4","target":"0"},{"source":"5","target":"3"},{"source":"7","target":"6"},{"source":"7","target":"0"}],"attributes":{"name":"Watts-Strogatz random graph","dim":1,"size":8,"nei":1,"p":0.33,"loops":false,"multiple":false}} 

这几乎是我想要的,但我需要配置两件事:

  1. 我希望节点 ID 从 1 开始,而不是 0。
  2. 我想删除链接中节点 ID 周围的引号(引号很好,因为它们在节点元素中),以便每个链接都这样写{"source": 1, "target": 2},而不是{"source": "1", "target": "2"}

我当然可以为这样的小型网络手动执行此操作,但这对于大型网络来说很乏味且不可扩展。有更好的方法R吗?

4

1 回答 1

1

将 json 转换为 R 列表并在写回 json 之前对数据进行必要的更改很容易。这是一个函数,它应该使用包中的d3_igraph工具来完成 的输出jsonlite

fix_d3_json <- function(json)
{
  dj <- jsonlite::fromJSON(data_json)
  dj$nodes$id   <- as.numeric(dj$nodes$id) + 1
  dj$links[[1]] <- as.numeric(dj$links[[1]]) + 1
  dj$links[[2]] <- as.numeric(dj$links[[2]]) + 1
  jsonlite::toJSON(dj)
}

所以现在你可以这样做:

library(igraph)
library(d3r)

# create small world network    
net <- sample_smallworld(size = 8, dim = 1, nei = 1, p = 0.33) 

# convert to json with directional edges   
data_json <- d3_igraph(as.directed(net))

# Fix json
data_json <- fix_d3_json(data_json)

data_json
#> {"nodes":[{"id":1},{"id":2},{"id":3},{"id":4},{"id":5},{"id":6},{"id":7},
#> {"id":8}],"links":[{"source":1,"target":6},{"source":1,"target":2},
#> {"source":2,"target":3},{"source":3,"target":4},{"source":2,"target":6},
#> {"source":3,"target":6},{"source":6,"target":7},{"source":1,"target":7},
#> {"source":6,"target":1},{"source":2,"target":1},{"source":3,"target":2},
#> {"source":4,"target":3},{"source":6,"target":2},{"source":6,"target":3},
#> {"source":7,"target":6},{"source":7,"target":1}],"attributes":
#> {"name":["Watts-Strogatz random graph"],"dim":[1],"size":[8],"nei":[1],
#> "p":[0.33],"loops":[false],"multiple":[false]}}
于 2020-06-30T12:39:12.667 回答