简体   繁体   English

R:如何创建多个分割数据矩阵?

[英]R: How to create multiple matrices of splited data?

I am using trade data (FAO) which I would like to turn into matrices (per Item and Year). 我正在使用贸易数据(FAO),我想将其转换为矩阵(按项目和年份)。 Therefore I've done a split: 因此,我进行了拆分:

# import is the original df
import_YI <- split(import, list(import$Item, import$Year))
import_YI_lap <- lapply(seq_along(import_YI), function(x) as.data.frame(import_YI[[x]])[, 1:11]) 

and the data looks like this (you can find test data at the end) : 数据看起来像这样(您可以在最后找到测试数据):

[[1]]
RC         PC       Item       Year    Value   
Argentina  Chile    Almonds    1996    1108  
Algeria    Spain    Almonds    1996    1  
....
[[2]]
....
[[3]]
....
[[n]]

I used the cast function (below) to create a matrix for almonds in 2012: 我在2012年使用了cast功能(如下)为杏仁创建了一个矩阵:

# import_almonds2012 is a test subset from import df (with import values for almonds in 2012)
RCPC <- cast(RC ~ PC, data =import_almonds2012, value = "Value")

Now my question: how can I do matrices of all Items/Years (~100 Items and 17 years!!) from the import_YI_lap df? 现在我的问题是:如何从import_YI_lap df中计算所有项目/年(〜100个项目和17年!)的import_YI_lap My problem is that I don't know (1) how to operate the levels/ojects in this df ( [[1]], [[2]]... ). 我的问题是我不知道(1)如何操作此df中的级别/对象( [[1]], [[2]]... )。 Or there a better way to split data or to save the splited df into objects? 还是有更好的方法来拆分数据或将拆分后的df保存到对象中? And (2) how to create all the needed matrices without coping thousend lines of code. (2)如何创建所有需要的矩阵而无需应付大量的代码行。 Loops? 循环? If yes, how?? 如果是,怎么办?

here a test-dataset: 这里是一个测试数据集:

import<- data.frame(RC=c("DE", "IT", "USA"),
                PC = c("BRA", "ARG"),
                Item = c("Almonds", "Apples"),
                Year = c(1996,1997,1998),
                Value = c(1,5,3,2,8,3))

import_YI <- split(import, list(import$Item, import$Year))
import_YI_lap <- lapply(seq_along(import_YI), function(x) as.data.frame(import_YI[[x]])[, 1:5])
import_YI_lap

没有数据很难进行测试,但是您可以尝试以下操作:

do.call(rbind,import_YI_lap)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM