R:如何使用cast函数在循环中创建矩阵? [英] R: How to create matrix in a loop using cast-function?

查看:311
本文介绍了R:如何使用cast函数在循环中创建矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 cast 函数在每年列表 code> reshape-package 。当我尝试这一年的一切都很好。查看代码(测试数据集如下!):

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)

结果是一个矩阵,包含2011年从原始国家

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

推荐答案

如@DavidArenburg评论,您应该使用 dcast 函数使用 value.var 参数从 reshape2 包中。

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")
}


$ b b

所以,你使用 list()(而不是一个值为零的变量)启动一个列表,然后添加每个dcast作为元素到该列表。

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.

输出:

> 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

这篇关于R:如何使用cast函数在循环中创建矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆