我试图将边缘列表转换为加权图(即保留边缘列表中的值)。这是我的边缘列表:
Reporter.Countries Partner.Countries Year Value
1 Afghanistan Canada 2017 0
2 Afghanistan Pakistan 2015 2
3 Afghanistan Slovakia 2018 0
4 Albania Iceland 2017 0
5 Algeria Senegal 2017 0
6 Argentina Bangladesh 2014. 112942
7 Argentina Belgium 2016. 0
8 Argentina Bolivia (Plurinational State of) 2016 7556
9 Argentina Brazil 2016 411.
10 Argentina Canada 2016. 364.
这是我正在使用的代码:
#import data and average years
soybean <- read.csv("soybean.csv")
library(dplyr)
soybean <- soybean %>%
group_by(Reporter.Countries, Partner.Countries) %>%
summarise_each(funs(mean))
#make edgelist
edgelist <- soybean %>%
select(Reporter.Countries, Partner.Countries, Year, Value)
edgelist$"Value" <- as.numeric(edgelist$"Value")
#converting to graph
g <- graph.data.frame(edgelist, directed=FALSE)
g <- set_edge_attr(g, "Value", value= edgelist$Value)
get.adjacency(g, type="both", attr="Value")
write.csv(as.matrix(get.adjacency(g)), file = "importedsoybean.csv", row.names = TRUE)
但是我的邻接矩阵以 1 和 2 结束,而不是边缘列表中的值。
它看起来像这样:
Afghanistan . . . . . . . . . . . . . . . . . . . . . . . . . 2 .
Albania . . . . . . . . . . . . . . . . . . . . . . . . . . .
Algeria . . . . . . . . . . 1 . . . . . 1 . . . . . . . . . .
Argentina . . . . . . . . 1 . 1 . . 2 . . 2 . . . . . .
我究竟做错了什么?
这是一个可重现的示例:
df <- read.table(header=TRUE,
text="Reporter.Countries Partner.Countries Year Value
1 Afghanistan Canada 2017 0
2 Afghanistan Pakistan 2015 2
3 Afghanistan Slovakia 2018 0
4 Albania Iceland 2017 0
5 Algeria Senegal 2017 0
6 Argentina Bangladesh 2014 112942
")
g <- graph.data.frame(df, directed=FALSE)
g <- set_edge_attr(g, "Value", value= edgelist$Value)
get.adjacency(g, type="both", attr="Value")
get.adjacency(g)
write.csv(as.matrix(get.adjacency(g)), file = "importedsoybeantext.csv", row.names = TRUE)