2014-04-02 70 views
0

我有一個data.frame,看起來像這樣:談到一個數據幀到多個圖形中的R

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

哪裏是'as.network'定義爲功能?還是來自包裝? –

+0

'庫(網絡)' - 更新了代碼,對不起。 – histelheim

+0

'install.packages(「network」)' – hrbrmstr

回答

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") 
相關問題