table

Methods

Method Reference: table.addvars

table: tblB = addvars (tblA, var1, …, varN)
table: tblB = addvars (…, 'After', location)
table: tblB = addvars (…, 'Before', location)
table: tblB = addvars (…, 'NewVariableNames', newNames)

Add new variables to a table.

tblB = addvars (tblA, var1, …, varN) adds new variables to the right of the last variable in table tblA. Each of the arrays specified by the input arguments var1, …, varN becomes a new variable and its name is derived from the input argument’s variable name or a default is created if the input argument is not a variable itself. The input arrays can be of any data type including a table as long as they have the same number of rows as tblA.

tblB = addvars (…, 'After', location) adds the new 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.

tblB = addvars (…, 'Before', location) adds the new 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.

tblB = addvars (…, 'NewVariableNames', newNames) renames the new variables added from the previous syntaxes according to the names specified by newNames, which can be a character vector, a cell array of character vectors or a string array. The number of names in newNames must be the same as the number of added variables.

Source Code: table

Example: 1

addvars inserts one or more variables into a table. Appended at the end by default, the new columns can be named with 'NewVariableNames' and may be of any type — here a datetime is added to a table of mixed variables.

 Name = string ({'Sanchez'; 'Johnson'; 'Li'});
 Age = [38; 43; 40];
 Gender = categorical ({'M'; 'M'; 'F'});
 T = table (Name, Age, Gender)
T =
  3x3 table

      Name       Age    Gender    
    _________    ___    ______    

    "Sanchez"     38         M    
    "Johnson"     43         M    
    "Li"          40         F
 Visit = datetime (2024, [1; 2; 3], [5; 6; 7]);
 addvars (T, Visit)
ans =
  3x4 table

      Name       Age    Gender       Visit       
    _________    ___    ______    ___________    

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

Use 'Before' or 'After' to place the new variable at a chosen position.

 addvars (T, logical ([1; 0; 1]), 'After', 'Age', 'NewVariableNames', {'Smoker'})
ans =
  3x4 table

      Name       Age    Smoker    Gender    
    _________    ___    ______    ______    

    "Sanchez"     38    true           M    
    "Johnson"     43    false          M    
    "Li"          40    true           F