Data analysis in Ruby: Daru
Ruby for science – that is what SciRuby is about, a community that builds gems for numbers, statistics and data (github.com/SciRuby); IRuby, which runs Ruby in Jupyter notebooks, belongs to it too. This lesson and the next two introduce three of their gems: tables, statistics and networks.
In lesson 69 pandas did tables, in Python. Daru (Data Analysis in RUby) does the same in Ruby itself, no Python needed. Sameer Deshmukh started it, and here too a table is called a DataFrame. Let's take the breakfast from back then:
install_gem "daru"
require "daru"
breakfast = Daru::DataFrame.new({
food: ["Bacon", "Eggs", "Toast", "Coffee"],
price: [4.5, 2.0, 1.5, 3.0],
quantity: [2, 3, 2, 4]
})Every key becomes a column, and its array fills it from top to bottom. The column names are symbols; Daru numbers the rows itself, 0 to 3 – the index. Below the cell, the course shows a DataFrame as a table.
Square brackets give you one column. Daru calls it a Vector:
breakfast[:price]A Vector is more than an array: it knows its index, and it does statistics. sum adds up, mean is the average, max the largest value:
prices = breakfast[:price]
[prices.sum, prices.mean, prices.max]$11 in all, $2.75 on average, $4.50 at most. What pandas does with whole columns, Daru does too: * multiplies two Vectors row by row, and []= stores the result as a new column. sort takes the columns to sort by as an array:
breakfast[:total] = breakfast[:price] * breakfast[:quantity]
breakfast.sort([:total], ascending: false)Coffee first: 4 cups at $3. Picking rows takes two steps, as in pandas, only "greater than" is called gt here – and there are lt (less than), eq (equal) and more. The question goes to every row, and where keeps the rows that answer yes:
pricey = breakfast[:price].gt(2) # gt: greater than
breakfast.where(pricey)Two rows remain, with their old numbers 0 and 3. to_a takes you back to Ruby – an ordinary array, to carry on with as always:
breakfast.where(pricey)[:food].to_aNow counting and grouping. These are a small diner's orders; frequencies counts how often each dish appears:
orders = Daru::DataFrame.new({
table: [1, 2, 1, 3, 2, 1],
food: ["Bacon", "Eggs", "Coffee", "Bacon", "Bacon", "Toast"],
price: [4.5, 2.0, 3.0, 4.5, 4.5, 1.5]
})
orders[:food].frequenciesBacon three times, everything else once. How much did each table spend? group_by(:table) puts each table's rows in a group, and sum adds up within each group – every column of numbers; the names of the dishes it leaves out:
orders.group_by(:table).sumTable 1 pays $9, table 2 $6.50, table 3 $4.50. Instead of sum there are mean, max, min and count too.
Data usually comes from a file. For a week, Chunky kept notes at an ice cream stand: how warm it was and how many scoops were sold – as CSV, one line per day. The cell writes the file and reads it back with from_csv:
File.write("ice_cream.csv", <<~CSV)
day,temperature,scoops
Mon,18,40
Tue,22,61
Wed,25,80
Thu,21,55
Fri,28,102
Sat,31,130
Sun,24,77
CSV
ice_cream = Daru::DataFrame.from_csv("ice_cream.csv")From a file, the column names arrive as strings, just as its first line has them: ice_cream["scoops"], not ice_cream[:scoops]. The numbers Daru recognised and converted.
describe sums up every column of numbers: how many values, their average (mean), their spread (std, the standard deviation – how far the values typically lie from the average), the smallest and the largest:
ice_cream.describe24 degrees and 78 scoops a day on average. Do the two go together? corr works out the correlation of every pair of columns: 1 means they rise in lockstep, 0 that they have nothing to do with each other, −1 that one falls when the other rises:
ice_cream.corr0.99 – the warmer, the more ice cream, almost as if drawn with a ruler. Whether the warmth sells the scoops, though, the number does not say: a correlation is not yet a cause. The next lesson carries on with chance and probability.
gem install daru – Daru is plain Ruby and runs anywhere; with Bundler, matrix and csv go in the Gemfile too, as they are no longer among Ruby's default gems. It draws charts with the gems nyaplot or gruff, and in IRuby, Ruby's kernel for Jupyter notebooks, DataFrames show up as tables, as here. There has been no new release since 2020; for big data there are now also Polars (written in Rust, and fast) and RedAmber. Daru comes under the BSD licence.
group_by and turn the result into a Ruby hash per_snack, like {"bacon" => …, "berries" => …, "egg" => …}.install_gem "daru"
require "daru"
snacks = Daru::DataFrame.new({
day: ["Mon", "Mon", "Tue", "Wed", "Wed", "Wed"],
snack: ["bacon", "berries", "bacon", "egg", "bacon", "berries"],
grams: [120, 80, 150, 60, 90, 40]
})
# per_snack = ... (a Ruby hash: snack => grams in all)