Julia Tables as Structs
Tables as structs means storing each row of a table as one struct value. A table is then a vector of those row values, and a column is the same field taken from every row.
A vector of structs is a table
Each Person value holds one row. The vector holds all three rows together.
struct Person
name::String
age::Int
end
rows = [Person("Ada", 36), Person("Bo", 41), Person("Cy", 29)]
println(length(rows))
println(rows[1].name)One field from every row is a column
This comprehension takes the age field from every row. The result is the age column.
struct Person
name::String
age::Int
end
rows = [Person("Ada", 36), Person("Bo", 41), Person("Cy", 29)]
ages = [r.age for r in rows]
println(ages[2])
println(sum(ages))Named tuples can hold rows too
Each named tuple holds one row without a struct definition. Field access works the same way.
rows = [(name = "Ada", age = 36), (name = "Bo", age = 41)]
println(length(rows))
println(rows[2].age)Example
struct Player
name::String
score::Int
end
players = [Player("Ada", 10), Player("Bo", 20), Player("Cy", 30)]
println(length(players))
println(players[2].name)
scores = [p.score for p in players]
println(scores[3])
println(sum(scores))Key points
- Row: One struct value holds all the values for one row.
- Table: A vector of struct values holds the whole table.
- Column: A column is one field taken from every row, in row order.
- Comprehension: A comprehension over the rows builds one column.
- Named tuple: A named tuple row works the same way without a struct definition.
In this example, players holds three rows as Player values. The code prints the row count and the second name, then builds the score column and prints its last value and its total.
Note
No extra package is needed, because plain structs already hold the rows.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
How do you build the age column from a vector of Person rows?