Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Table column with String

Tags:

julia

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.

like image 239
fact Avatar asked Jul 18 '26 21:07

fact


1 Answers

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)

EDIT

if your column comes as a String cast it to a Symbol:

julia> getproperty(t, Symbol("valueA"))
3-element Vector{Int64}:
 10
 20
 30
like image 58
Przemyslaw Szufel Avatar answered Jul 23 '26 08:07

Przemyslaw Szufel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!