I have a data.frame that has 4 columns (sender, receiver, year and value). I want to create a list which has for each year an adjacency matrix of the sender and the receiver containing the value.
A MVE would be
df = data.frame(sender = c("a","a","b","c","d","d","d","b","e","e"),
receiver = c("b","d","a","a","b","a","c","e","c","a"),
value = 1:10,
year= c(2000,2000,2001,2002,2002,2002,2003,2003,2003,2004))
Also I have a country list I need it to match with
country_list = data.frame(country = c("a","b","c","d","e")
What I have tried looks like this. My problem is that not the correct values are shown in the subsequent adjacency matrix.
transfer_list <- list()
for (t in 2000:2004){
matrix<-matrix(0,5,5)
rownames(matrix)<-country_list[1:5,1]
colnames(matrix)<-country_list[1:5,1]
year=which(df[,4]==t)
dyad=df[year,c(1,2)]
for (i in 1:dim(dyad)[1]){
partner1<-which(country_list[,1]==dyad[i,1])
partner2<-which(country_list[,1]==dyad[i,2])
matrix[partner1, partner2]<-df[i,3]
}
transfer_list[[t-1999]]=matrix
}
The result for 2004 should be a 10 for the transfer from e to a but is:
> transfer_list[[5]]
a b c d e
a 0 0 0 0 0
b 0 0 0 0 0
c 0 0 0 0 0
d 0 0 0 0 0
e 1 0 0 0 0
What is my error?