Subscript

subscript(_:)

Retrieves or adds an untyped column with the specified name.

Declaration

subscript(columnName: String) -> MLUntypedColumn { get set }

Parameters

columnName

The name of the column to extract from or add to the data table.

Return Value

A new MLUntypedColumn with the specified name, if it exists; otherwise an invalid column.

Discussion

Use this subscript to retrieve an MLUntypedColumn or add a new one to the data table.

A table on the left with two columns plus a third semi-opaque column. The first two columns are named "Planet" and "Distance (AU)" (for Astronomical Units). The third column has a dash where its name should be. The first column has values like "Mercury", "Venus", and "Earth"; the second column has values like "0.39", "0.72", and "1.00"; and the third column has dashes where its values should be.  An arrow points to the right from the table to a second table with a same "Planet" and "Distance (AU)" columns along with a third, fully opaque column named "Distance (km)" (for kilometers). The third column contains values such as "5834170".

For example, to extract, convert, and add a column as shown above, begin by creating a data table.

let data: [String: MLDataValueConvertible] = [
    "Planet": ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"],
    "Distance (AU)": [0.39, 0.72, 1.00, 1.52, 5.20, 9.54, 19.22, 30.06]
]

var table = try MLDataTable(dictionary: data)

After creating the table, extract a column.

let distanceInAU = table["Distance (AU)"]

Use the untyped column’s multiplication operator to create a new column of data.

// Create a new column of Doubles by multiplying all the the values in
// `distanceInAU` by 149,597,870.7 (the number of km in an astronomical unit)
// `* (a: MLDataColumn<Double>, b: Double) -> MLDataColumn<Double>` operator
let distanceInKm = (distanceInAU * 149_597_870.700)

Finally, use the subscript(_:) to add the new column to a table with a different name.

table["Distance (km)"] = distanceInKm

See Also

Accessing Columns

subscript<T>(String, T.Type) -> MLDataColumn<T>?

Retrieves a column with the specified name and type.

subscript<Element>(String) -> MLDataColumn<Element>

Retrieves or adds a typed column with the specified name.