3

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.

1 Answer 1

1

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
2
  • Thanks! Kinda, but I think my main problem is that I'm given the column names as strings and I need to convert them to something that allows me to access the table column. So what I would need is something like getproperty(t, "valueA") resp. something like columns(t)[:"valueA"].
    – fact
    Commented Nov 19, 2022 at 15:32
  • 1
    Edited the answer and added a relevant comment Commented Nov 19, 2022 at 15:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.