How can I Stack data in a Table
显示 更早的评论
Hi,
My data looks like this (A 3046X5 table):
Date | Excess_Stock | Excess_Index | FD_Stock | FD_Index
731910 | 0.01 | 0.02 | 0.05 | 0.06
731911 | 0.02 | 0.04 | 0.04 | 0.4
. .
. .
My question: Is it possible to get the data stack the following way
Date SecName Excess FD
731910 Stock 0.01 0.05
731911 Stock 0.02 0.04
731910 Index 0.02 0.06
731911 Index 0.04 0.4
采纳的回答
更多回答(1 个)
Peter Perkins
2016-9-21
There's a function specifically to do this: stack. In this case, you are stacking two groups of variables, so it's not quite as simple as the simplest case, but it's pretty simple.
% set up some fake data
>> vnames = {'Date' 'Excess_Stock' 'Excess_Index' 'FD_Stock' 'FD_Index'};
>> tunstacked = array2table([[1;2;3] rand(3,4)],'VariableNames',vnames)
tunstacked =
Date Excess_Stock Excess_Index FD_Stock FD_Index
____ ____________ ____________ ________ ________
1 0.77491 0.084436 0.80007 0.18185
2 0.8173 0.39978 0.43141 0.2638
3 0.86869 0.25987 0.91065 0.14554
% stack the two Excess vars and the two FD vars
>> tstacked = stack(tunstacked,{{'Excess_Stock' 'Excess_Index'} {'FD_Stock' 'FD_Index'}});
>> tstacked.Properties.VariableNames = {'Date' 'SecName' 'Excess' 'FD'};
>> tstacked.SecName = categorical(tstacked.SecName,[2 3],{'Stock' 'Index'})
tstacked =
Date SecName Excess FD
____ _______ ________ _______
1 Stock 0.77491 0.80007
1 Index 0.084436 0.18185
2 Stock 0.8173 0.43141
2 Index 0.39978 0.2638
3 Stock 0.86869 0.91065
3 Index 0.25987 0.14554
2 个评论
Peter Perkins
2016-9-23
By "that", I think you mean, "stacking more than one set of variables at a time." Fair enough, I've made a note to have this made more obvious in the documentation.
It is also possible to call stack twice and horizontally concatenate the two results.
类别
在 帮助中心 和 File Exchange 中查找有关 Tables 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!