8. Data and Statistics Packages#
8.1. Overview#
This lecture explores some of the key packages for working with data and doing statistics in Julia.
In particular, we will examine the DataFrame
object in detail (i.e., construction, manipulation, querying, visualization, and nuances like missing data).
While Julia is not an ideal language for pure cookie-cutter statistical analysis, it has many useful packages to provide those tools as part of a more general solution.
This list is not exhaustive, and others can be found in organizations such as JuliaStats, JuliaData, and QueryVerse.
using LinearAlgebra, Statistics
using DataFrames, RDatasets, DataFramesMeta, CategoricalArrays, Query
using GLM
8.2. DataFrames#
A useful package for working with data is DataFrames.jl.
The most important data type provided is a DataFrame
, a two dimensional array for storing heterogeneous data.
Although data can be heterogeneous within a DataFrame
, the contents of the columns must be homogeneous
(of the same type).
This is analogous to a data.frame
in R, a DataFrame
in Pandas (Python) or, more loosely, a spreadsheet in Excel.
There are a few different ways to create a DataFrame.
8.2.1. Constructing and Accessing a DataFrame#
The first is to set up columns and construct a dataframe by assigning names
using DataFrames, RDatasets # RDatasets provides good standard data examples from R
# note use of missing
commodities = ["crude", "gas", "gold", "silver"]
last_price = [4.2, 11.3, 12.1, missing]
df = DataFrame(commod = commodities, price = last_price)
Row | commod | price |
---|---|---|
String | Float64? | |
1 | crude | 4.2 |
2 | gas | 11.3 |
3 | gold | 12.1 |
4 | silver | missing |
Columns of the DataFrame
can be accessed by name using df.col
, as below
df.price
4-element Vector{Union{Missing, Float64}}:
4.2
11.3
12.1
missing
Note that the type of this array has values Union{Missing, Float64}
since it was created with a missing
value.
df.commod
4-element Vector{String}:
"crude"
"gas"
"gold"
"silver"
The DataFrames.jl
package provides a number of methods for acting on DataFrame
’s, such as describe
.
DataFrames.describe(df)
Row | variable | mean | min | median | max | nmissing | eltype |
---|---|---|---|---|---|---|---|
Symbol | Union… | Any | Union… | Any | Int64 | Type | |
1 | commod | crude | silver | 0 | String | ||
2 | price | 9.2 | 4.2 | 11.3 | 12.1 | 1 | Union{Missing, Float64} |
While often data will be generated all at once, or read from a file, you can add to a DataFrame
by providing the key parameters.
nt = (commod = "nickel", price = 5.1)
push!(df, nt)
Row | commod | price |
---|---|---|
String | Float64? | |
1 | crude | 4.2 |
2 | gas | 11.3 |
3 | gold | 12.1 |
4 | silver | missing |
5 | nickel | 5.1 |
Named tuples can also be used to construct a DataFrame
, and have it properly deduce all types.
nt = (t = 1, col1 = 3.0)
df2 = DataFrame([nt])
push!(df2, (t = 2, col1 = 4.0))
Row | t | col1 |
---|---|---|
Int64 | Float64 | |
1 | 1 | 3.0 |
2 | 2 | 4.0 |
In order to modify a column, access the mutating version by the symbol df[!, :col]
.
df[!, :price]
5-element Vector{Union{Missing, Float64}}:
4.2
11.3
12.1
missing
5.1
Which allows modifications, like other mutating !
functions in julia.
df[!, :price] *= 2.0 # double prices
5-element Vector{Union{Missing, Float64}}:
8.4
22.6
24.2
missing
10.2
As discussed in the next section, note that the fundamental types, is propagated, i.e. missing * 2 === missing
.
8.2.2. Working with Missing#
As we discussed in fundamental types, the semantics of missing
are that mathematical operations will not silently ignore it.
In order to allow missing
in a column, you can create/load the DataFrame
from a source with missing
’s, or call allowmissing!
on a column.
allowmissing!(df2, :col1) # necessary to add in a for col1
push!(df2, (t = 3, col1 = missing))
push!(df2, (t = 4, col1 = 5.1))
Row | t | col1 |
---|---|---|
Int64 | Float64? | |
1 | 1 | 3.0 |
2 | 2 | 4.0 |
3 | 3 | missing |
4 | 4 | 5.1 |
We can see the propagation of missing
to caller functions, as well as a way to efficiently calculate with non-missing data.
@show mean(df2.col1)
@show mean(skipmissing(df2.col1))
mean(df2.col1) = missing
mean(skipmissing(df2.col1)) = 4.033333333333333
4.033333333333333
And to replace the missing
df2.col1 .= coalesce.(df2.col1, 0.0) # replace all missing with 0.0
4-element Vector{Float64}:
3.0
4.0
0.0
5.1
8.2.3. Manipulating and Transforming DataFrames#
One way to do an additional calculation with a DataFrame
is to tuse the @transform
macro from DataFramesMeta.jl
.
using DataFramesMeta
f(x) = x^2
df2 = @transform(df2, :col2=f.(:col1))
Row | t | col1 | col2 |
---|---|---|---|
Int64 | Float64 | Float64 | |
1 | 1 | 3.0 | 9.0 |
2 | 2 | 4.0 | 16.0 |
3 | 3 | 0.0 | 0.0 |
4 | 4 | 5.1 | 26.01 |
8.2.4. Categorical Data#
For data that is categorical
using CategoricalArrays
id = [1, 2, 3, 4]
y = ["old", "young", "young", "old"]
y = CategoricalArray(y)
df = DataFrame(id = id, y = y)
Row | id | y |
---|---|---|
Int64 | Cat… | |
1 | 1 | old |
2 | 2 | young |
3 | 3 | young |
4 | 4 | old |
levels(df.y)
2-element Vector{String}:
"old"
"young"
8.2.5. Visualization, Querying, and Plots#
The DataFrame
(and similar types that fulfill a standard generic interface) can fit into a variety of packages.
One set of them is the QueryVerse.
Note: The QueryVerse, in the same spirit as R’s tidyverse, makes heavy use of the pipeline syntax |>
.
x = 3.0
f(x) = x^2
g(x) = log(x)
@show g(f(x))
@show x |> f |> g; # pipes nest function calls
g(f(x)) = 2.1972245773362196
(x |> f) |> g = 2.1972245773362196
To give an example directly from the source of the LINQ inspired Query.jl
using Query
df = DataFrame(name = ["John", "Sally", "Kirk"],
age = [23.0, 42.0, 59.0],
children = [3, 5, 2])
x = @from i in df begin
@where i.age > 50
@select {i.name, i.children}
@collect DataFrame
end
Row | name | children |
---|---|---|
String | Int64 | |
1 | Kirk | 2 |
While it is possible to just use the Plots.jl
library, there are other options for displaying tabular data – such as VegaLite.jl.
8.3. Statistics and Econometrics#
While Julia is not intended as a replacement for R, Stata, and similar specialty languages, it has a growing number of packages aimed at statistics and econometrics.
Many of the packages live in the JuliaStats organization.
A few to point out
StatsBase has basic statistical functions such as geometric and harmonic means, auto-correlations, robust statistics, etc.
StatsFuns has a variety of mathematical functions and constants such as pdf and cdf of many distributions, softmax, etc.
8.3.1. General Linear Models#
To run linear regressions and similar statistics, use the GLM package.
using GLM
x = randn(100)
y = 0.9 .* x + 0.5 * rand(100)
df = DataFrame(x = x, y = y)
ols = lm(@formula(y~x), df) # R-style notation
StatsModels.TableRegressionModel{LinearModel{GLM.LmResp{Vector{Float64}}, GLM.DensePredChol{Float64, CholeskyPivoted{Float64, Matrix{Float64}, Vector{Int64}}}}, Matrix{Float64}}
y ~ 1 + x
Coefficients:
────────────────────────────────────────────────────────────────────────
Coef. Std. Error t Pr(>|t|) Lower 95% Upper 95%
────────────────────────────────────────────────────────────────────────
(Intercept) 0.259136 0.0139093 18.63 <1e-33 0.231533 0.286739
x 0.896694 0.0141923 63.18 <1e-80 0.86853 0.924858
────────────────────────────────────────────────────────────────────────
To display the results in a useful tables for LaTeX and the REPL, use RegressionTables for output similar to the Stata package esttab and the R package stargazer.
using RegressionTables
regtable(ols)
# regtable(ols, renderSettings = latexOutput()) # for LaTex output
----------------------
y
----------------------
(Intercept) 0.259***
(0.014)
x 0.897***
(0.014)
----------------------
N 100
R2 0.976
----------------------
8.3.2. Fixed Effects#
While Julia may be overkill for estimating a simple linear regression, fixed-effects estimation with dummies for multiple variables are much more computationally intensive.
For a 2-way fixed-effect, taking the example directly from the documentation using cigarette consumption data
using FixedEffectModels
cigar = dataset("plm", "Cigar")
cigar.StateCategorical = categorical(cigar.State)
cigar.YearCategorical = categorical(cigar.Year)
fixedeffectresults = reg(cigar,
@formula(Sales~NDI + fe(StateCategorical) +
fe(YearCategorical)),
weights = :Pop, Vcov.cluster(:State))
regtable(fixedeffectresults)
------------------------------------------
Sales
------------------------------------------
NDI -0.005***
(0.001)
------------------------------------------
StateCategorical Fixed Effects Yes
YearCategorical Fixed Effects Yes
------------------------------------------
N 1,380
R2 0.803
Within-R2 0.139
------------------------------------------