Reputation: 557
How can one pass the name of a table column to a function and access this column in the function? For example, if we define
using TypedTables
t = Table(time = [1,2,3], valueA = [10, 20, 30])
then I can simply access columns as follows
t.time
where I explicitly spell out the column name. However, what I want to do is pass the table and some column names to a function and access them within the function, the table columns
function fn(cnames::Array{String,1}, t::Table)
for c in cnames
#get column c from table t
#do something with column c
end
end
I don't know what to do in the for-loop. Simply putting
t.c
or
t.Symbol(c)
doesn't work.
Upvotes: 3
Views: 115
Reputation: 42234
I think that you what you are looking for is getproperty
:
julia> getproperty(t, :valueA)
3-element Vector{Int64}:
10
20
30
columns
also includes a tuple with all columns of the table so you could try as well:
julia> columns(t)[:valueA]
3-element Vector{Int64}:
10
20
30
Actually looking at the package source code this is exactly how getproperty
is defined so you are free to use either option:
@inline Base.getproperty(t::Table, name::Symbol) = getproperty(columns(t), name)
if your column comes as a String
cast it to a Symbol
:
julia> getproperty(t, Symbol("valueA"))
3-element Vector{Int64}:
10
20
30
Upvotes: 1