我的data.frame
看起来像这样:
row.names id actor event time end
4427 1494 Locke23rus merged 1 1
4428 1494 Locke23rus closed 1 1
4429 1494 Locke23rus referenced 1 1
4492 1397 brixen discussed 2 2
4493 1397 brixen closed 2 2
...
可以找到完整的数据集here。接下来,加载数据和库:
dat <- my data # i.e. the data above
library(plyr)
library(network)
使用以下函数(由@hrbrmstr建议)我可以将这些数据转换为网络图形对象:
makeNetwork <- function(dat)
{
dat2 <<- ddply(dat, .(id), function(d){
data.frame(
event = d$event[-1],
from = d$actor[-NROW(d)],
to = d$actor[-1],
time = paste(d$time[-NROW(d)], d$time[-1], sep = "-")
)
})
dat3 <- cbind(dat2["from"], dat2["to"])
dat4 <- as.network(dat3[, 1:2])
(dat4)
}
但是,我只想删除具有相同id的初始数据集的行,使用公共ID在每组行上运行网络图生成代码,然后将生成的网络图对象放入列表,像这样:
list(graph_object_id1494, graph_object_id1397, ...)
所以我跑:
graph_list <- dlply(dat, .(id), .fun=makeNetwork)
生成以下错误消息:
Error in `[.data.frame`(dat2, "from") : undefined columns selected
如何正确创建图形对象列表?
答案 0 :(得分:0)
以下是我如何使其发挥作用:
# Make a raw graph dataset
makeNetworkData <- function(dat)
{
dat2 <- ddply(dat, .(id), function(d){
data.frame(
event = d$event[-1],
from = d$actor[-NROW(d)],
to = d$actor[-1],
time = paste(d$time[-NROW(d)], d$time[-1], sep = "-")
)
})
}
# apply function to make a list
graph_list <- dlply(dat, .(id), makeNetworkData)
# delete all data.frames (entries in the list) where nrow()=0
nr <- sapply(graph_list, nrow)
graph_list <- graph_list[nr > 0]
makeNetworkGraph <- function(graph_list){
output <- as.network(graph_list[, 3:4], loops = TRUE)
(output)
}
# Turn raw data in list to graph objects
graph_objects <- llply(graph_list, makeNetworkGraph)
# apply any SNA statistic to all entries in the list
hierarchy_list <- llply(graph_objects, hierarchy, measure="krackhardt")