• Stars
    star
    105
  • Rank 316,783 (Top 7 %)
  • Language
    R
  • License
    Other
  • Created about 5 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

BRowse Over Longitudinal Data Graphically and Analytically in R

brolgar

Lifecycle: stable R-CMD-check CRAN status Codecov test coverage

brolgar helps you browse over longitudinal data graphically and analytically in R, by providing tools to:

  • Efficiently explore raw longitudinal data
  • Calculate features (summaries) for individuals
  • Evaluate diagnostics of statistical models

This helps you go from the “plate of spaghetti” plot on the left, to “interesting observations” plot on the right.

Installation

Install from GitHub with:

# install.packages("remotes")
remotes::install_github("njtierney/brolgar")

Or from the R Universe with:

# Enable this universe
options(repos = c(
    njtierney = 'https://njtierney.r-universe.dev',
    CRAN = 'https://cloud.r-project.org')
    )

# Install some packages
install.packages('brolgar')

Using brolgar: We need to talk about data

There are many ways to describe longitudinal data - from panel data, cross-sectional data, and time series. We define longitudinal data as:

individuals repeatedly measured through time.

The tools and workflows in brolgar are designed to work with a special tidy time series data frame called a tsibble. We can define our longitudinal data in terms of a time series to gain access to some really useful tools. To do so, we need to identify three components:

  1. The key variable in your data is the identifier of your individual.
  2. The index variable is the time component of your data.
  3. The regularity of the time interval (index). Longitudinal data typically has irregular time periods between measurements, but can have regular measurements.

Together, time index and key uniquely identify an observation.

The term key is used a lot in brolgar, so it is an important idea to internalise:

The key is the identifier of your individuals or series

Identifying the key, index, and regularity of the data can be a challenge. You can learn more about specifying this in the vignette, “Longitudinal Data Structures”.

The wages data

The wages data is an example dataset provided with brolgar. It looks like this:

wages
#> # A tsibble: 6,402 x 9 [!]
#> # Key:       id [888]
#>       id ln_wages    xp   ged xp_since_ged black hispanic high_grade unemploy_…¹
#>    <int>    <dbl> <dbl> <int>        <dbl> <int>    <int>      <int>       <dbl>
#>  1    31     1.49 0.015     1        0.015     0        1          8        3.21
#>  2    31     1.43 0.715     1        0.715     0        1          8        3.21
#>  3    31     1.47 1.73      1        1.73      0        1          8        3.21
#>  4    31     1.75 2.77      1        2.77      0        1          8        3.3 
#>  5    31     1.93 3.93      1        3.93      0        1          8        2.89
#>  6    31     1.71 4.95      1        4.95      0        1          8        2.49
#>  7    31     2.09 5.96      1        5.96      0        1          8        2.6 
#>  8    31     2.13 6.98      1        6.98      0        1          8        4.8 
#>  9    36     1.98 0.315     1        0.315     0        0          9        4.89
#> 10    36     1.80 0.983     1        0.983     0        0          9        7.4 
#> # … with 6,392 more rows, and abbreviated variable name ¹​unemploy_rate

And under the hood, it was created with the following setup:

wages <- as_tsibble(x = wages,
                    key = id,
                    index = xp,
                    regular = FALSE)

Here as_tsibble() takes wages, and a key, and index, and we state the regular = FALSE (since there are not regular time periods between measurements). This turns the data into a tsibble object - a powerful data abstraction made available in the tsibble package by Earo Wang, if you would like to learn more about tsibble, see the official package documentation or read the paper.

Efficiently exploring longitudinal data

Exploring longitudinal data can be challenging when there are many individuals. It is difficult to look at all of them!

You often get a “plate of spaghetti” plot, with many lines plotted on top of each other. You can avoid the spaghetti by looking at a random subset of the data using tools in brolgar.

sample_n_keys()

In dplyr, you can use sample_n() to sample n observations, or sample_frac() to look at a fraction of observations.

brolgar builds on this providing sample_n_keys() and sample_frac_keys(). This allows you to take a random sample of n keys using sample_n_keys(). For example:

set.seed(2019-7-15-1300)
wages %>%
  sample_n_keys(size = 5) %>%
  ggplot(aes(x = xp,
             y = ln_wages,
             group = id)) + 
  geom_line()

And what if you want to create many of these plots?

Clever facets: facet_sample()

facet_sample() allows you to specify the number of keys per facet, and the number of facets with n_per_facet and n_facets.

By default, it splits the data into 12 facets with 5 per facet:

set.seed(2019-07-23-1937)
ggplot(wages,
       aes(x = xp,
           y = ln_wages,
           group = id)) +
  geom_line() +
  facet_sample()

Under the hood, facet_sample() is powered by sample_n_keys() and stratify_keys().

You can see more facets (e.g., facet_strata()) and data visualisations you can make in brolgar in the Visualisation Gallery.

Finding features in longitudinal data

Sometimes you want to know what the range or a summary of a variable for each individual. We call these summaries features of the data, and they can be extracted using the features function, from fabletools.

For example, if you want to answer the question “What is the summary of wages for each individual?”. You can use features() to find the five number summary (min, max, q1, q3, and median) of ln_wages with feat_five_num:

wages %>%
  features(ln_wages,
           feat_five_num)
#> # A tibble: 888 × 6
#>       id   min   q25   med   q75   max
#>    <int> <dbl> <dbl> <dbl> <dbl> <dbl>
#>  1    31 1.43   1.48  1.73  2.02  2.13
#>  2    36 1.80   1.97  2.32  2.59  2.93
#>  3    53 1.54   1.58  1.71  1.89  3.24
#>  4   122 0.763  2.10  2.19  2.46  2.92
#>  5   134 2.00   2.28  2.36  2.79  2.93
#>  6   145 1.48   1.58  1.77  1.89  2.04
#>  7   155 1.54   1.83  2.22  2.44  2.64
#>  8   173 1.56   1.68  2.00  2.05  2.34
#>  9   206 2.03   2.07  2.30  2.45  2.48
#> 10   207 1.58   1.87  2.15  2.26  2.66
#> # … with 878 more rows

This returns the id, and then the features.

There are many features in brolgar - these features all begin with feat_. You can, for example, find those whose ln_wages values only increase or decrease with feat_monotonic:

wages %>%
  features(ln_wages, feat_monotonic)
#> # A tibble: 888 × 5
#>       id increase decrease unvary monotonic
#>    <int> <lgl>    <lgl>    <lgl>  <lgl>    
#>  1    31 FALSE    FALSE    FALSE  FALSE    
#>  2    36 FALSE    FALSE    FALSE  FALSE    
#>  3    53 FALSE    FALSE    FALSE  FALSE    
#>  4   122 FALSE    FALSE    FALSE  FALSE    
#>  5   134 FALSE    FALSE    FALSE  FALSE    
#>  6   145 FALSE    FALSE    FALSE  FALSE    
#>  7   155 FALSE    FALSE    FALSE  FALSE    
#>  8   173 FALSE    FALSE    FALSE  FALSE    
#>  9   206 TRUE     FALSE    FALSE  TRUE     
#> 10   207 FALSE    FALSE    FALSE  FALSE    
#> # … with 878 more rows

You can read more about creating and using features in the Finding Features vignette. You can also see other features for time series in the feasts package.

Linking individuals back to the data

Once you have created these features, you can join them back to the data with a left_join, like so:

wages %>%
  features(ln_wages, feat_monotonic) %>%
  left_join(wages, by = "id") %>%
  ggplot(aes(x = xp,
             y = ln_wages,
             group = id)) +
  geom_line() + 
  gghighlight(increase)
#> Warning in left_join(., wages, by = "id"): Each row in `x` is expected to match at most 1 row in `y`.
#> ℹ Row 1 of `x` matches multiple rows.
#> ℹ If multiple matches are expected, set `multiple = "all"` to silence this
#>   warning.
#> Warning: Tried to calculate with group_by(), but the calculation failed.
#> Falling back to ungrouped filter operation...
#> label_key: id
#> Too many data series, skip labeling

Other helper functions

n_obs()

Return the number of observations total with n_obs():

n_obs(wages)
#> n_obs 
#>  6402

n_keys()

And the number of keys in the data using n_keys():

n_keys(wages)
#> [1] 888

Finding the number of observations per key.

You can also use n_obs() inside features to return the number of observations for each key:

wages %>%
  features(ln_wages, n_obs)
#> # A tibble: 888 × 2
#>       id n_obs
#>    <int> <int>
#>  1    31     8
#>  2    36    10
#>  3    53     8
#>  4   122    10
#>  5   134    12
#>  6   145     9
#>  7   155    11
#>  8   173     6
#>  9   206     3
#> 10   207    11
#> # … with 878 more rows

This returns a dataframe, with one row per key, and the number of observations for each key.

This could be further summarised to get a sense of the patterns of the number of observations:

library(ggplot2)
wages %>%
  features(ln_wages, n_obs) %>%
  ggplot(aes(x = n_obs)) + 
    geom_bar()

wages %>%
  features(ln_wages, n_obs) %>%
  summary()
#>        id            n_obs       
#>  Min.   :   31   Min.   : 1.000  
#>  1st Qu.: 3332   1st Qu.: 5.000  
#>  Median : 6666   Median : 8.000  
#>  Mean   : 6343   Mean   : 7.209  
#>  3rd Qu.: 9194   3rd Qu.: 9.000  
#>  Max.   :12543   Max.   :13.000

Further Reading

brolgar provides other useful functions to explore your data, which you can read about in the exploratory modelling and Identify Interesting Observations vignettes. As a taster, here are some of the figures you can produce:

#> Warning in left_join(., wages, by = "id"): Each row in `x` is expected to match at most 1 row in `y`.
#> ℹ Row 1 of `x` matches multiple rows.
#> ℹ If multiple matches are expected, set `multiple = "all"` to silence this
#>   warning.
#> Warning: Tried to calculate with group_by(), but the calculation failed.
#> Falling back to ungrouped filter operation...
#> label_key: id
#> Too many data series, skip labeling
#> Warning in left_join(., wages, by = "id"): Each row in `x` is expected to match at most 1 row in `y`.
#> ℹ Row 1 of `x` matches multiple rows.
#> ℹ If multiple matches are expected, set `multiple = "all"` to silence this
#>   warning.

Related work

One of the sources of inspiration for this work was the lasangar R package by Bryan Swihart (and paper).

For even more expansive time series summarisation, make sure you check out the feasts package (and talk!).

Contributing

Please note that the brolgar project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.

A Note on the API

This version of brolgar was been forked from tprvan/brolgar, and has undergone breaking changes to the API.

Acknowledgements

Thank you to Mitchell O’Hara-Wild and Earo Wang for many useful discussions on the implementation of brolgar, as it was heavily inspired by the feasts package from the tidyverts. I would also like to thank Tania Prvan for her valuable early contributions to the project, as well as Stuart Lee for helpful discussions. Thanks also to Ursula Laa for her feedback on the package structure and documentation.

More Repositories

1

naniar

Tidy data structures, summaries, and visualisations for missing data
R
630
star
2

rmd4sci

Rmarkdown for Scientists
RMarkdown
126
star
3

syn

syn - the thesaurus
R
51
star
4

maxcovr

Tools in R to make it easier to solve the Maximal Coverage Location Problem
R
41
star
5

ukpolice

🇬🇧 🚓 R package to pull police data from the uk police data repository 🚓 🇬🇧
R
35
star
6

qmd4sci

quarto for scientists
TeX
29
star
7

broomstick

🌲 broom helpers for decision tree methods (rpart, randomForest, and more!) 🌲
R
29
star
8

mmcc

Fast, tidy functions for mcmc diagnostics and summaries, built with data.table
R
23
star
9

monash-colour-in-graphics

Slides for my talk, "The use of colour in graphics"
CSS
21
star
10

ozviridis

Demonstrate the process of improving BoM heatmaps
R
19
star
11

rstudioconf20

CSS
18
star
12

palap

symmetric (reflective, palindromic) colour palettes (rev(palap) == palap)
R
18
star
13

user2018-missing-data-tutorial

HTML
14
star
14

treezy

🌴 Make handling decision trees easy. Treezy. 🌴
R
14
star
15

mputr

Package for handling multiple imputations in a tidy format
R
13
star
16

flipper

Make it easy to flip through R packages from CRAN, Bioconductor, and GitHub
R
13
star
17

genbib

Generate bib (.bib) bibliography files on the fly
R
12
star
18

ishihara

Create Ishihara plates in R
R
11
star
19

conmat

Create Contact Matrices from Population Data
R
11
star
20

rmd-errors

A collection of rmarkdown files with bugs, to practice solving.
11
star
21

ttiq-simulation

R
10
star
22

greta-course-notes

Course notes for greta
R
10
star
23

rjournal-brolgar

rjournal article for brolgar
R
9
star
24

neato

A set of function that I use somewhat regularly
R
9
star
25

cranalmanac

Access the Archives of CRAN
R
7
star
26

datadevtools

Development tools for sharing data
R
7
star
27

cranscan

scan cran for useful repositories with a Shiny app to help you swipe left/right
R
7
star
28

chaletex

Tools to extract latex packages from a .tex file and install them
TeX
7
star
29

A-Simple-Guide-to-S3-Methods

R Journal Submission: A short guide to using S3 Methods in R
TeX
6
star
30

burgr-reproducible-talk

Slides for the August 2016 burgr meetup about reproducibility
HTML
6
star
31

talk-unsw-rse

SCSS
5
star
32

marean

marean: A structure for (ma)king (re)producible (an)alysis
Makefile
5
star
33

ozroaddeaths

Access data from Australian Road Deaths Database
R
5
star
34

rmd4sci-materials

Materials to get started for rmarkdown for scientists
TeX
4
star
35

wombat19

CSS
4
star
36

bomr

An R package to make it easier to access data from the Australian Bureau of Meterology
HTML
4
star
37

njtcv

my CV
TeX
4
star
38

rcproposal2018

Proposal for RConsortium - https://www.r-consortium.org/projects/call-for-proposals
HTML
4
star
39

njt-talks

A GitHub Template for my slides
3
star
40

talk-user-2022

https://njt-user-2022.netlify.app/#1
SCSS
3
star
41

sinquote

replace strange quotes from places like gdocs/excel/msword with normal quotes
R
3
star
42

user-2018-maxcovr-talk

The repository for my user 2018 talk
HTML
3
star
43

ysc2019

Slides for talk on brolgar at YSC 2019
CSS
3
star
44

tierneyn.github.io

HTML
3
star
45

thesisdown-tufte

A repo for getting a thesis into tufte format using bookdown
HTML
3
star
46

talk-qut-ec

Greta talk at QUT Early Career Bayes
SCSS
2
star
47

target-pop-pyramid

R
2
star
48

teaching-data

repo containing datasets used in teaching
R
2
star
49

sirtensor

SIR simulation using tensorflow (work in progress)
R
2
star
50

website-md-cv

Borrowed markdown CV template from https://github.com/blmoore/md-cv
HTML
2
star
51

yahtsee

Yet Another Hierachical Time Series Extension and Expansion
R
2
star
52

explore-sir-targets

playing around with SIR model in targets: https://staff.math.su.se/hoehle/blog/2020/03/16/flatteningthecurve.html
R
2
star
53

jsm21

Slides for my talk at JSM 2021
SCSS
2
star
54

example-greta-targets

example greta workflow using targets
R
2
star
55

njt_bmj_md

Rmd for "Using decision trees to understand structure in missing data"
TeX
2
star
56

quokka

A NUMBATs / Monash meeting to discuss tidyeval, rlang, quosures, quasiquotation in an effort to make it simpler and easier to understand
HTML
2
star
57

numbat-data

repo for my data talk at NUMBAT
CSS
2
star
58

talk-canterbury-2022

Talk at University of Canterbury 2022
R
2
star
59

tidy-missing-data-paper

Repository for the paper "Expanding tidy data principles to facilitate missing data exploration, visualization and assessment of imputations"
HTML
2
star
60

quarto-gh-pages

quarto-gh-pages
TeX
1
star
61

dotfiles

Shell
1
star
62

limbodata

Example data for spatial data analysis project
R
1
star
63

yas

1
star
64

jtt

Just Three Things: code from the screencast, "Just Three Things"
R
1
star
65

mex

This is the repository for the upcoming package mex, the (m)issingness (ex)plorer.
R
1
star
66

ozfire

Repository of fire related vis, pulling data from https://github.com/AusNZOpenRes/AusFires
1
star
67

nt-park-status

How open are the NT parks?
R
1
star
68

ozvis19

CSS
1
star
69

rethinking

a repo on my work for the Statistical Rethinking book
HTML
1
star
70

rstudioconf22

rstudioconf 2022
1
star
71

talks

These talks are now here >>>
JavaScript
1
star
72

njtmisc

Misc functions I find useful
R
1
star
73

my-binder-test

R
1
star
74

freerange-covid

Converting Peter Ellis' COVID modelling code into a drake workflow
R
1
star
75

praiseme3

A package to deliver praise, because sometimes, it is just what we need.
R
1
star
76

aawt

Exploration of AAWT track and temperatures
R
1
star
77

ssa-2018-rethinking-teaching-computing

Slides for the SSA talk I gave at the SSA VIC 2018/07 meetup on Statistical Education
HTML
1
star
78

anu-seminar

CSS
1
star
79

ropensci-visdat

draft blog post
HTML
1
star
80

broombayes

broom helpers for Bayesian statistical models (BUGS, JAGS, STAN, and more)
R
1
star
81

codelens

Assist exploring and improving large code bases.
R
1
star
82

angletr-rmd-gh

Feedback form for the course: >>
TeX
1
star
83

example-quarto-book

TeX
1
star