I am desperately trying to populate a matrix with values ββfrom a data frame. This is trade data, so the data frame looks something like this:
country1 country2 value
1 Afghanistan Albania 30
2 Afghanistan Albania 81
3 Afghanistan China 5
4 Albania Germany 6
5 China Germany 8
6 China Turkey 900
7 Germany Turkey 12
8 Germany USA 3
9 Germany Zambia 700
Using the unique and sort commands, I created a list of all the countries that appear in df (and converted them to a matrix):
countries_sorted
[1,] "Afghanistan"
[2,] "Albania"
[3,] "China"
[4,] "Germany"
[5,] "Turkey"
[6,] "USA"
[7,] "Zambia"
Using this βlistβ, I created an empty trading matrix (7x7):
Afghanistan Albania China Germany Turkey USA Zambia
Afghanistan NA NA NA NA NA NA NA
Albania NA NA NA NA NA NA NA
China NA NA NA NA NA NA NA
Germany NA NA NA NA NA NA NA
Turkey NA NA NA NA NA NA NA
USA NA NA NA NA NA NA NA
Zambia NA NA NA NA NA NA NA
Now, I hopelessly cannot fill this matrix with numbers / sums from the df value column. I tried something like this:
a<-cast(df, country1~country2 , sum)
which works to some extent, but the matrix does not preserve its original 7x7 format, so I need a matrix where the diagonal is 0s.
> a
country1 Albania China Germany Turkey USA Zambia
1 Afghanistan 111 5 0 0 0 0
2 Albania 0 0 6 0 0 0
3 China 0 0 8 900 0 0
4 Germany 0 0 0 12 3 700
Please someone with a solution ????