How to programatically construct a ComponentArray or NamedTuple?

As the title says, how can I programatically construct a ComponentArray or NamedTuple from a vector of strings (or symbols) and a vector of numbers?
from this

n = ["a", "b", "c"]
x = [1, 2, 3]

I want to get this

ca = ComponentArray(a = 1, b = 2, c = 3)

or this

nt = (a = 1, b = 2, c = 3)

The application I have in mind is to construct a ComponentArray or NamedTuple from a DataFrame:

df = DataFrame(a = 1, b = 2, c = 3)

(I think the way for constructing either ComponentArrays or NamedTuples would be the same)

This works:

julia> (;Pair.(Symbol.(n),x)...)
(a = 1, b = 2, c = 3)
1 Like

Another possibility:

NamedTuple(Symbol.(n) .=> x)
2 Likes

Convert any table (eg DataFrame) to a namedtuple-of-arrays: Tables.columntable(...); to an array-of-namedtuples: Tables.rowtable(...). These may be more helpful for your specific usecase.

4 Likes

This is fantastic!

Similar to @sijo’s answer, you can just splat the pairs after a semicolon. This will work both for making NamedTuples or ComponentArrays directly:

julia> (; (Symbol.(n) .=> x)...)
(a = 1, b = 2, c = 3)

julia> ComponentArray(; (Symbol.(n) .=> x)...)
ComponentVector{Int64}(a = 1, b = 2, c = 3)
1 Like