【问题标题】:Create longitudinal data from a list of igraph objects in R从 R 中的 igraph 对象列表创建纵向数据
【发布时间】:2017-07-14 14:57:17
【问题描述】:

我正在用 R 对公司网络进行分析,并试图将我的 igraph 结果导出到数据框中。

这是一个可重现的例子:

library(igraph)
sample <- data.frame(ID = 1:8, org_ID = c(5,4,1,2,2,2,5,7), mon = c("199801", "199802","199802","199802","199904","199912","200001", "200012"))

create.graphs <- function(df){
g <- graph.data.frame(d = df, directed = TRUE)
g <- simplify(g, remove.multiple = FALSE, remove.loops = TRUE)
E(g)$weight <- count_multiple(g)

#calculate global values
g$centrality <- centralization.degree(g)
#calculate local values
g$indegree <- degree(g, mode = "in",
                   loops = FALSE, normalized = FALSE)

return(g)
}

df.list <- split(sample, sample$mon)
g <- lapply(df.list, create.graphs)

如您所见,我有好几个月的图表。我想将其导出为纵向数据,其中每一行代表一个月(每个 ID),每一列代表相应的网络度量。

到目前为止,我已经设法创建了一个数据框,但不是如何通过图表列表运行它并将其放入合适的格式。另一个问题可能是图表有不同数量的节点(有些大约有 25 个,有些超过 40 个),但理论上我的回归模型应该将其识别为缺失。

output <- data.frame(Centrality = g$`199801`$centrality,
        Indegree = g$`199801`$indegree)
output
summary(output)

我尝试为此编写一个类似于上面的函数,但不幸的是无济于事。

提前感谢您阅读本文,非常感谢任何帮助

【问题讨论】:

  • 您可以尝试使用sapplylapply 将其分解为列表形式:sapply(g, function(x){x$centrality})lapply(g, function(x){x$indegree})。这可能更接近愿望形式。
  • 谢谢你,Dave2e 并为迟到的回复道歉,我周末很忙 :-) apply 函数似乎是正确的方法。一个快速的问题,因为我还在学习:data.frame &lt;- lapply(g, function(x){x$indegree}) 将阅读:将列表 g 的每个元素应用于 data.frame,其中函数指定每个元素的哪一部分 ($)(在本例中为度数)?我发现很难理解编码的某些部分,并且想要更好地理解。

标签: r igraph data-export longitudinal


【解决方案1】:

我想分享我是如何解决它的(感谢 Dave2e 的建议)。

请注意,ci$monat 在原始数据中定义了我的时间段,因此每个时间点一行。

sumarTable <- data.frame(time = unique(ci$monat))

sumarTable$indegree <- lapply(g, function(x){x$indegree})
sumarTable$outdegree <- lapply(g, function(x){x$outdegree})
sumarTable$constraint <- lapply(g, function(x){x$constraint})

编辑: 为了导出这些值,我不得不“展平”列表:

sumarTable$indegree <- vapply(sumarTable$indegree, paste, collapse = ", ", character(1L))
sumarTable$outdegree <- vapply(sumarTable$outdegree, paste, collapse = ", ", character(1L))
sumarTable$constraint <- vapply(sumarTable$constraint, paste, collapse = ", ", character(1L))

【讨论】:

  • 嗨冻糕,你可能是对的,谢谢你指出这一点。我必须承认,我既是 R 新手,也是纵向数据分析的新手,所以我不能 100% 确定如何实现正确的结构 - 到目前为止非常令人困惑,但在它起作用时会有所收获。现在我每个时间点都有一行,并且在列中根据str 列出。他们读了@​​987654324@,所以他们不应该充当向量吗?还是我走错了方向? (编辑:我可能应该提到我想在之后使用 Stata 中的数据)
  • 我不熟悉igraph,但听起来还可以。是的,数据框中的每一列都应该是原子向量。如果您可以write.csv() 没有问题,则没有嵌套数据。编码愉快!
  • 感谢您的回复!我确实收到此错误:Error in .External2(C_writetable, x, file, nrow(x), p, rnames, sep, eol, : unimplemented type 'list' in 'EncodeElement' 使用 write.csv() 时,所以我想我应该以某种方式尝试扩展向量,因为 R 将它们视为列表?我假设这会使数据本质上是长格式?
猜你喜欢
  • 2021-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
  • 1970-01-01
  • 2015-10-14
  • 1970-01-01
相关资源
最近更新 更多