table

Methods

Method Reference: table.mergevars

table: tblB = mergevars (tblA, vars)
table: tblB = mergevars (tblA, vars, Name, Value)

Merge table variables into a single multicolumn variable.

tblB = mergevars (tblA, vars) combines the table variables in tblA specified by vars to create a new multicolumn variable in tblB. All other variables in tblA are copied to tblB unaltered. By default, the name of the merged variable in tblB takes the form VarN, where N is the position of the first variable in tblA among those to be merged, which is also the location of the merged variable in tblB.

Note that merging variables with a 'string' data type variable will result in a multicolumn variable of 'string' data type, by initially converting all other to-be-merged variables into 'string' data type.

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

tblB = mergevars (…, Name, Value) further specifies additional parameters for merging table variables with the following Name-Value paired arguments.

  • 'NewVariableName' specifies the name of the merged variable in tblB, which must be unique. 'NewVariableName' must be either a cellstr or string scalar or a character vector.
  • 'MergeAsTable' specifies whether the selected variables should be merged into a multicolumn variable (default) or into a table nested into a variable, which is useful for variables that cannot be concatenated due to incompatible variable types. 'MergeAsTable' must be either a boolean scalar or a numeric scalar value of 1 (true) or 0 (false).

Source Code: table

Example: 1

mergevars combines several variables into one multi-column variable — the inverse of splitvars. Name the merged variable with 'NewVariableName'.

 T = table ([38; 43; 40], [124; 109; 125], [93; 77; 83], ...
            'VariableNames', {'Age', 'Systolic', 'Diastolic'})
T =
  3x3 table

    Age    Systolic    Diastolic    
    ___    ________    _________    

     38         124           93    
     43         109           77    
     40         125           83
 mergevars (T, {'Systolic', 'Diastolic'}, 'NewVariableName', 'BloodPressure')
ans =
  3x2 table

    Age    BloodPressure    
    ___    _____________    

     38        124    93    
     43        109    77    
     40        125    83