我想将A国的产品编号(第1栏)和年份(第2栏)与同一产品和B国的年份相匹配,以便能够减去该年度和该产品国家的相应贸易号码(第3栏减去第6栏)。当找不到对应的人时,我想把那个职位扔出去。
在下面链接中的示例中,我手动完成了这一操作,直到第22行(除减去贸易数字外)。例如,下面第(23)行说,产品030420在1995年的交易价值为2.823,但该年该产品的交易没有记录在B国,因此我希望删除该邮件。相应地,在B国,产品030420的贸易记录在1994年,但在A国没有对应的,因此该职位也应删除。
尽管下面示例中的数据显示在excel中(我试图在excel中解决这个问题,但它变得很棘手),我现在已经将数据存储在Matlab中的一个矩阵中,并希望为它编写一个代码,但我对Matlab/coding非常陌生。用语言来说,可能是这样的:
然后,当然,对其余的样本重复这个过程。
示例:
如果有人想读这篇短文,并有任何建议,我们会非常感激的。
发布于 2011-06-22 12:49:10
在这个解决方案中,我将使用统计工具箱中的数据集数组。
考虑以下两个示例CSV文件(类似于您的Excel文件,但我将这两个国家划分为不同的文件):
countryA.csv
ProductCode,Year,TradeValue
011111,1992,5.934
011111,1999,7.05
022222,2002,5.2
033333,2005,16.6
033333,2006,55
countryB.csv
ProductCode,Year,TradeValue
011111,1992,24.5
011111,1999,25
033333,2005,33.11
033333,2006,44.92
044444,2010,10.8
下面的代码读取两个数据集,并使用(ProductCode,年份)作为行键执行内部ProductCode,然后计算匹配行的两个交易值的差异:
%# read datasets (note we are reading ProductCode/Year as strings to preserve leading zeros)
dA = dataset('File','countryA.csv', 'Delimiter',',', 'Format','%s %s %f','ReadVarNames',true);
dB = dataset('File','countryB.csv', 'Delimiter',',', 'Format','%s %s %f','ReadVarNames',true);
%# inner join (keep only rows that exist in both datasets)
ds = join(dA, dB, 'keys',{'ProductCode' 'Year'}, 'type','inner', 'MergeKeys',true);
%# add a new variable for the difference
dsTradeDiff = dataset(ds.TradeValue_left - ds.TradeValue_right, 'VarNames','TradeDifference');
ds = cat(2, ds, dsTradeDiff);
生成的数据集:
ds =
ProductCode Year TradeValue_left TradeValue_right TradeDifference
'011111' '1992' 5.934 24.5 -18.566
'011111' '1999' 7.05 25 -17.95
'033333' '2005' 16.6 33.11 -16.51
'033333' '2006' 55 44.92 10.08
编辑:--这是实现上述目标的另一种方法,只使用基本内置的MATLAB函数:
%# read countryA
fid = fopen('countryA.csv','rt');
C = textscan(fid, '%s %s %f', 'Delimiter',',', 'HeaderLines',1);
fclose(fid);
[prodCodeA yearA tradeValA] = deal(C{:});
%# read countryB
fid = fopen('countryB.csv','rt');
C = textscan(fid, '%s %s %f', 'Delimiter',',', 'HeaderLines',1);
fclose(fid);
[prodCodeB yearB tradeValB] = deal(C{:});
%# build rows merged-keys
keysA = strcat(prodCodeA,yearA);
keysB = strcat(prodCodeB,yearB);
%# match rows
[idx1 loc1] = ismember(keysA,keysB);
[idx2 loc2] = ismember(keysB,keysA);
%# compute result for intersection of rows
tradeDiff = tradeValA(loc2(idx2)) - tradeValB(loc1(idx1))
同样的结果:
tradeDiff =
-18.566
-17.95
-16.51
10.08
https://stackoverflow.com/questions/6438193
复制相似问题