I try to make a yearly country import matrix out of a yearly list
using the cast
function in the reshape-package
. As I try this for a single year everything works fine. See code (test-dataset below!) :
OCTC2011 <- cast(OC ~ TC, data =Import_Year[["2011"]], value = "Value")
The result is a matrix containing the import-values of the year 2011 from the origin-country (OC) (rows) to the target-country (TC) (columns).
However, as I use a large dataset consisting of different products for different years, I want to put this procedure in a loop. I tried following:
library(reshape)
OCTC <- 0
for(i in 1:length(unique(Import_Year)))
{
OCTC[i] <- cast(OC ~ TC, data =Import_Year[[i]], value = "Value")
}
Which delivers the warning: number of items to replace is not a multiple of replacement length
, probably due to a wrong indexing as I'am hardly familiar with loops.
Here I produced a simple dataset for my problem:
OC <- c("A", "A", "B", "B", "C", "C", "D", "D")
TC <- c("Z", "Z", "Y", "Y", "X", "X", "W", "W")
Value <- c(1,2,3,4,5,6,7,8)
Year <- c(2010,2011)
df_import <- data.frame(OC,TC,Value, Year)
Import_Year <- split(df_import, df_import$Year)
I appreciate every comment on this. Thanks