2014-05-19 50 views
1

我的工作區中有很多大型數據集數組(從.mat文件加載)。將數據集列轉換爲obsnames

的最小工作的例子是這樣的

>> 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

+0

你能上傳一個示例文件嗎? – Cici

+0

@Cici,我編輯了我的問題以包含一個鏈接(最後一行)到示例文件。希望你能幫助。謝謝! – apsql

+0

無法打開您的文件...也許嘗試添加一個-v7.3標籤,當你保存? – Cici

回答

0

你幾乎在那裏,你得到的錯誤信息基本上是說,Obsname必須是字符串。在你的情況下,'日期'變量是包含雙打的單元格數組。所以你只需要將它們轉換爲字符串。

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. 
+0

謝謝@Cici,但即使我的問題不是明確的(我的不好),我實際上想問問是否存在一個更容易或更快(或兩者)的方式來獲得相同的結果_(如函數)。這個疑問來自於這樣一個事實,就我所知,用於導入數據的GUI(例如,來自csv)不允許設置ObsNames(運行R2013a),而且我仍然需要熟悉讀取/保存/加載命令。 – apsql

+0

順便說一句,我會upvote你的答案,如果我得到足夠的聲譽:) – apsql

+0

我看到,你可能能夠使用set('Obsname',Obsname),在Obsname轉換爲單元格數組的字符串.http:// www。 mathworks.com/help/stats/dataset.set.html – Cici

1

實際上它應該是很容易的(但事實上,我讀了你的問題意味着有同樣的問題,我首先查找的文檔之前GOOGLE了它...;)

當加載數據集,使用下面的命令(當然要適應你的情況):

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

'ReadObsNames'的默認值是false。它採用第一列的標題並將其保存在文件或範圍中,作爲A.Properties.DimNames中第一個維的名稱。 (請參見Documentation,章節:「使用文本文件或Excel電子表格作爲輸入時可用的名稱/值對」)

我無法下載您的示例文件,但如果您尚未解決問題,只是嘗試建議的解決方案,並告訴它是否工作。很高興,如果我能幫忙。