问题描述
我试图将边缘列表转换为加权图(即将值保留在边缘列表中)。这是我的边缘列表:
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,attr="Value")
get.adjacency(g)
write.csv(as.matrix(get.adjacency(g)),file = "importedsoybeantext.csv",row.names = TRUE)
解决方法
我设法通过以下方式解决了这个问题:
f <- as.matrix(get.adjacency(g,type="both",attr="Value"))
write.csv(f,file = "importedsoybean.csv",row.names = TRUE)