table

Methods

Method Reference: table.movevars

table: tblB = movevars (tblA, vars)
table: tblB = movevars (…, 'After', location)
table: tblB = movevars (…, 'Before', location)

Move variables in a table.

tblB = movevars (tblA, vars) moves the variables specified by vars to the end of the input table tblA.

vars can be any of the following types.

  • a character vector specifying a single variable.
  • a cell array of character vectors specifying a single or multiple variables.
  • a string array specifying a single or multiple variables.
  • a numeric array of integer values indexing the variables to be moved.
  • a logical vector of the same length as the width of the table tblA indexing as true the variables to be moved.
  • a vartype object used to create a subscript that selects variables of a specified type.

tblB = movevars (…, 'After', location) moves the selected variables after (i.e. to the right of) the table variable specified in location, which can be a character vector, a string scalar, a scalar integer value, or even a logical vector with width (tblA) elements, as long as it indexes a single variable in tblA which is not selected by vars.

tblB = movevars (…, 'Before', location) moves the selected variables before (i.e. to the left of) the table variable specified in location, which can be a character vector, a string scalar, a scalar integer value, or even a logical vector with width (tblA) elements, as long as it indexes a single variable in tblA which is not selected by vars.

Source Code: table

Example: 1

movevars reorders variables, placing one (or several) 'Before' or 'After' another — the data is unchanged, only the column order shifts.

 Name = string ({'Sanchez'; 'Johnson'; 'Li'});
 Age = [38; 43; 40];
 Gender = categorical ({'M'; 'M'; 'F'});
 Visit = datetime (2024, [1; 2; 3], [5; 6; 7]);
 T = table (Name, Age, Gender, Visit)
T =
  3x4 table

      Name       Age    Gender       Visit       
    _________    ___    ______    ___________    

    "Sanchez"     38         M    05-Jan-2024    
    "Johnson"     43         M    06-Feb-2024    
    "Li"          40         F    07-Mar-2024
 movevars (T, 'Visit', 'After', 'Name')
ans =
  3x4 table

      Name          Visit       Age    Gender    
    _________    ___________    ___    ______    

    "Sanchez"    05-Jan-2024     38         M    
    "Johnson"    06-Feb-2024     43         M    
    "Li"         07-Mar-2024     40         F

Move a variable to the front by placing it before the first one.

 movevars (T, 'Gender', 'Before', 'Name')
ans =
  3x4 table

    Gender      Name       Age       Visit       
    ______    _________    ___    ___________    

         M    "Sanchez"     38    05-Jan-2024    
         M    "Johnson"     43    06-Feb-2024    
         F    "Li"          40    07-Mar-2024