将数据集列转换为obsnames

时间:2014-05-19 09:55:27

标签: matlab dataset

我的工作区中有很多大型数据集数组(从.mat文件加载)。

最小的工作示例就像这样

>> disp(old_ds)

Date        firm1       firm2       firm3       firm4
734692      880,0       102,1       32,7        204,2
734695      880,0       102,0       30,9        196,4
734696      880,0       100,0       30,9        200,2
734697      880,0       101,4       30,9        200,2
734698      880,0       100,8       30,9        202,2

其中第一行(带有字符串)已经是数据集中的标题,即如果我运行old_ds.Properties.VarNames,它们就已经显示了。
我想知道是否有一种简单和/或快速的方法将第一列作为ObsNames。

作为第一种方法,我想到了“导出”数据矩阵(示例中的第2列到第5列),日期向量,然后创建一个新的数据集,其中行具有名称。 即:

>> mat = double(old_ds(:,2:5));         % taking the data, making it a matrix array

>> head = old_ds.Properties.VarNames    % saving headers
>> head(1,1) = [];                      % getting rid of 'Date' from head

>> dates = dataset2cell(old_ds(:,1));   % taking dates as column cell array
>> dates(1) = [];                       % getting rid of 'Date' from dates

>> new_ds = mat2dataset(mat,'VarNames',head,'ObsNames',dates);

除了最后一行返回以下错误之外,......

Error using setobsnames (line 25)
NEWNAMES must be a nonempty string or a cell array of nonempty strings.

Error in dataset (line 377)
    a = setobsnames(a,obsnamesArg);

Error in mat2dataset (line 75)
    d = dataset(vars{:},args{:});

...我会找到一个解决方案,然后创建一个函数(比如为我拥有的所有22个数据集数组推广流程),然后运行22次函数(每个数据集数组一次)。 从透视角度来看,每个数据集都有7660行和多个列,范围从2到1320.

我不知道我怎么能(如果可以的话)使数据集直接“吃掉”第一列为ObsNames。

任何人都可以给我一个提示吗?

编辑:附上 sample file

2 个答案:

答案 0 :(得分:1)

实际上它应该很容易(但事实上我正在阅读你的问题意味着遇到同样的问题,我在查阅文档之前先用Google搜索...;)

加载数据集时,请使用以下命令(当然根据您的情况进行调整):

cell_dat{1} = dataset('File', 'YourDataFile.csv', 'Delimiter', ';',...
    'ReadObsNames', true);

'ReadObsNames'默认为false。它采用第一列的标题并将其作为A.Properties.DimNames中第一个维度的名称保存在文件或范围中。 (参见Documentation,章节:“使用文本文件或Excel电子表格作为输入时可用的名称/值对”)

我无法下载您的示例文件,但如果您还没有解决问题,请尝试建议的解决方案,并告诉它是否有效。很高兴,如果我能提供帮助。

答案 1 :(得分:0)

你几乎就在那里,你得到的错误信息基本上是说Obsname必须是字符串。在您的情况下,'dates'变量是包含双精度的单元格数组。所以你只需要将它们转换为字符串。

mat = double(piHU(:,2:end));         % taking the data, making it a matrix array
head = piHU.Properties.VarNames    % saving headers
head(1) = [];                      % getting rid of 'Date' from head

dates = dataset2cell(piHU(:,1));   % taking dates as column cell array, here dates are of type double. try typing on the command window class(dates{2}), you can see the output is double.
dates(1) = [];  % getting rid of 'Date' from dates
dates_str=cellfun(@(s) num2str(s),dates,'UniformOutput',false); % convert dates to string, now try typing class(dates_str{2}), the output should be char

new_ds = mat2dataset(mat,'VarNames',head,'ObsNames',dates_str); % construct new dataset.