I have a table in MATLAB with variable titles equal to:
titles = {'TZ_1', 'TZ_2', 'TZ_3', 'DATE'};
Is there any way to move change the data to have the DATE
before TZ_1
?
titles = {'DATE', 'TZ_1', 'TZ_2', 'TZ_3'};
I can see movevars
in the 2022 version, but I am currently running the 2016 version.
Any help would be appreciated - I am relatively new to MATLAB.
CodePudding user response:
You can do it by name
% Set up example data
t = table(1,2,3,4, 'VariableNames',{'TZ_1', 'TZ_2', 'TZ_3', 'DATE'})
% Specify the column ordering you want
titles = {'DATE', 'TZ_1', 'TZ_2', 'TZ_3'};
% Rearrange the table
t = t( :, titles );
You can of course do this without the intermediate variable
t = t( :, {'DATE', 'TZ_1', 'TZ_2', 'TZ_3'});
Extension:
If you just know you want 'DATE'
at the front regardless where it currently is in the order, you could do something like
titles = [{'DATE'}, setdiff(t.Properties.VariableNames, {'DATE'}, 'stable')];
t = t( :, titles );
CodePudding user response:
Yes, you can do this with indexing. (If you look at the implementation of movevars
, that is exactly what it does).
>> t = table(1,2,3,4, 'VariableNames',{'TZ_1', 'TZ_2', 'TZ_3', 'DATE'})
t =
1×4 table
TZ_1 TZ_2 TZ_3 DATE
____ ____ ____ ____
1 2 3 4
>> t(:,[4, 1:3])
ans =
1×4 table
DATE TZ_1 TZ_2 TZ_3
____ ____ ____ ____
4 1 2 3