table

Methods

Method Reference: table.splitvars

table: tblB = splitvars (tblA)
table: tblB = splitvars (tblA, vars)
table: tblB = splitvars (…, 'NewVariableNames', NewNames)

Split multicolumn variables in a table.

tblB = splitvars (tblA) splits multicolumn variables in tblA so that they are single-column variables in tblB, while all single-column variables in tblA are copied to tblB unaltered. Each newly created single-column variable in tblB is uniquely named by joining the name of its parent multicolumn variable in tblA and the corresponding column number. If a variable in tblA contains a table, then each variable of this nested table is returned as a newly created variable in tblB. By default, these variables retain their original name in the nested table, unless there are duplicate names, in which case the name of the nested table is also used. If the nested table in tblA contains a multicolumn variable, then the newly created variable in tblB is also multicolumnar.

tblB = splitvars (tblA, vars) splits only the variables in tblA specified by vars. If left empty, it defaults to all variables that can be split. Single-column variables specified in vars are copied unaltered.

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 split.
  • a logical vector of the same length as the width of the table tblA indexing as true the variables to be split.
  • a vartype object used to create a subscript that selects variables of a specified type.

tblB = splitvars (…, 'NewVariableNames', NewNames) assigns new names to the variables that are split out of tblA and copied to tblB. NewNames can be specified as a cell array of character vectors and/or string arrays.

Source Code: table

Example: 1

splitvars expands a multi-column variable into several single-column variables — the inverse of mergevars. Auto-generated names get a numeric suffix; pass 'NewVariableNames' to choose your own.

 BloodPressure = [124, 93; 109, 77; 125, 83];
 T = table ([38; 43; 40], BloodPressure, 'VariableNames', {'Age', 'BP'})
T =
  3x2 table

    Age       BP        
    ___    _________    

     38    124    93    
     43    109    77    
     40    125    83
 splitvars (T, 'BP')
ans =
  3x3 table

    Age    BP_1    BP_2    
    ___    ____    ____    

     38     124      93    
     43     109      77    
     40     125      83

Name the resulting columns explicitly.

 splitvars (T, 'BP', 'NewVariableNames', {'Systolic', 'Diastolic'})
ans =
  3x3 table

    Age    Systolic    Diastolic    
    ___    ________    _________    

     38         124           93    
     43         109           77    
     40         125           83