R: How to create matrix in a loop using cast-function?

混江龙づ霸主 提交于 2019-12-24 12:44:32

问题


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


回答1:


As @DavidArenburg comments you should probably use the dcast function from the reshape2 package using the value.var argument.

Apart from that the loop should be something like this in order to work:

library(reshape2)
OCTC <- list()
for(i in 1:length(unique(Import_Year))) 
{
  OCTC[[length(OCTC)+1]] <- dcast(OC ~ TC, data =Import_Year[[i]], value.var = "Value")
}

So, you initiate a list using list() (and not a variable with the value of zero) and then you add each dcast as an element to that list.

Output:

> OCTC
[[1]]
  OC  W  X  Y  Z
1  A NA NA NA  1
2  B NA NA  3 NA
3  C NA  5 NA NA
4  D  7 NA NA NA

[[2]]
  OC  W  X  Y  Z
1  A NA NA NA  2
2  B NA NA  4 NA
3  C NA  6 NA NA
4  D  8 NA NA NA


来源:https://stackoverflow.com/questions/32760067/r-how-to-create-matrix-in-a-loop-using-cast-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!