Learn R Programming

⚠️There's a newer version (0.11.1) of this package.Take me there.

tidytable

Why tidytable?

  • tidyverse-like syntax
  • Fast functions built using two high performance packages: data.table and the tidyverse’s vctrs
  • Compatibility with the tidy evaluation framework

Installation

Install the released version from CRAN with:

install.packages("tidytable")

Or install the development version from GitHub with:

# install.packages("devtools")
devtools::install_github("markfairbanks/tidytable")

General syntax

tidytable uses verb.() syntax to replicate tidyverse functions:

library(tidytable)

df <- data.table(x = 1:3, y = 4:6, z = c("a", "a", "b"))

df %>%
  select.(x, y, z) %>%
  filter.(x < 4, y > 1) %>%
  arrange.(x, y) %>%
  mutate.(double_x = x * 2,
          x_plus_y = x + y)
#> # A tidytable: 3 × 5
#>       x     y z     double_x x_plus_y
#>   <int> <int> <chr>    <dbl>    <int>
#> 1     1     4 a            2        5
#> 2     2     5 a            4        7
#> 3     3     6 b            6        9

A full list of functions can be found here.

Using “group by”

Group by calls are done by using the .by argument of any function that has “by group” functionality.

  • A single column can be passed with .by = z
  • Multiple columns can be passed with .by = c(y, z)
df %>%
  summarize.(avg_x = mean(x),
             count = n(),
             .by = z)
#> # A tidytable: 2 × 3
#>   z     avg_x count
#>   <chr> <dbl> <int>
#> 1 a       1.5     2
#> 2 b       3       1

.by vs. group_by()

tidytable follows data.table semantics where .by must be called each time you want a function to operate “by group”.

Below is some example tidytable code that utilizes .by that we’ll then compare to its dplyr equivalent. The goal is to grab the first two rows of each group using slice.(), then add a group row number column using mutate.():

library(tidytable)

df <- data.table(x = c("a", "a", "a", "b", "b"))

df %>%
  slice.(1:2, .by = x) %>%
  mutate.(group_row_num = row_number(), .by = x)
#> # A tidytable: 4 × 2
#>   x     group_row_num
#>   <chr>         <int>
#> 1 a                 1
#> 2 a                 2
#> 3 b                 1
#> 4 b                 2

Note how .by is called in both slice.() and mutate.().

Compared to a dplyr pipe chain that utilizes group_by(), where each function operates “by group” until ungroup() is called:

library(dplyr)

df <- tibble(x = c("a", "a", "a", "b", "b"))

df %>%
  group_by(x) %>%
  slice(1:2) %>%
  mutate(group_row_num = row_number()) %>%
  ungroup()
#> # A tibble: 4 × 2
#>   x     group_row_num
#>   <chr>         <int>
#> 1 a                 1
#> 2 a                 2
#> 3 b                 1
#> 4 b                 2

Note that the ungroup() call is unnecessary in tidytable.

tidyselect support

tidytable allows you to select/drop columns just like you would in the tidyverse by utilizing the tidyselect package in the background.

Normal selection can be mixed with all tidyselect helpers: everything(), starts_with(), ends_with(), any_of(), where(), etc.

df <- data.table(
  a = 1:3,
  b1 = 4:6,
  b2 = 7:9,
  c = c("a", "a", "b")
)

df %>%
  select.(a, starts_with("b"))
#> # A tidytable: 3 × 3
#>       a    b1    b2
#>   <int> <int> <int>
#> 1     1     4     7
#> 2     2     5     8
#> 3     3     6     9

To drop columns use a - sign:

df %>%
  select.(-a, -starts_with("b"))
#> # A tidytable: 3 × 1
#>   c    
#>   <chr>
#> 1 a    
#> 2 a    
#> 3 b

These same ideas can be used whenever selecting columns in tidytable functions - for example when using count.(), drop_na.(), across.(), pivot_longer.(), etc.

A full overview of selection options can be found here.

Using tidyselect in .by

tidyselect helpers also work when using .by:

df <- data.table(
  a = 1:3,
  b = c("a", "a", "b"),
  c = c("a", "a", "b")
)

df %>%
  summarize.(avg_a = mean(a), .by = where(is.character))
#> # A tidytable: 2 × 3
#>   b     c     avg_a
#>   <chr> <chr> <dbl>
#> 1 a     a       1.5
#> 2 b     b       3

Tidy evaluation compatibility

Tidy evaluation can be used to write custom functions with tidytable functions. The embracing shortcut {{ }} works, or you can use enquo() with !! if you prefer:

df <- data.table(x = c(1, 1, 1), y = c(1, 1, 1), z = c("a", "a", "b"))

add_one <- function(data, add_col) {
  data %>%
    mutate.(new_col = {{ add_col }} + 1)
}

df %>%
  add_one(x)
#> # A tidytable: 3 × 4
#>       x     y z     new_col
#>   <dbl> <dbl> <chr>   <dbl>
#> 1     1     1 a           2
#> 2     1     1 a           2
#> 3     1     1 b           2

The .data and .env pronouns also work within tidytable functions:

var <- 10

df %>%
  mutate.(new_col = .data$x + .env$var)
#> # A tidytable: 3 × 4
#>       x     y z     new_col
#>   <dbl> <dbl> <chr>   <dbl>
#> 1     1     1 a          11
#> 2     1     1 a          11
#> 3     1     1 b          11

A full overview of tidy evaluation can be found here.

dt() helper

The dt() function makes regular data.table syntax pipeable, so you can easily mix tidytable syntax with data.table syntax:

df <- data.table(x = 1:3, y = 4:6, z = c("a", "a", "b"))

df %>%
  dt(, .(x, y, z)) %>%
  dt(x < 4 & y > 1) %>%
  dt(order(x, y)) %>%
  dt(, double_x := x * 2) %>%
  dt(, .(avg_x = mean(x)), by = z)
#> # A tidytable: 2 × 2
#>   z     avg_x
#>   <chr> <dbl>
#> 1 a       1.5
#> 2 b       3

Speed Comparisons

For those interested in performance, speed comparisons can be found here.

Copy Link

Version

Install

install.packages('tidytable')

Monthly Downloads

2,522

Version

0.8.0

License

MIT + file LICENSE

Issues

Pull Requests

Stars

Forks

Maintainer

Last Published

June 11th, 2022

Functions in tidytable (0.8.0)

arrange_across.

Arrange by a selection of variables
c_across.

Combine values from multiple columns
bind_cols.

Bind data.tables by row and column
context

Context functions
crossing.

Create a data.table from all unique combinations of inputs
dt

Pipeable data.table call
across.

Apply a function across a selection of columns
mutate_rowwise.

Add/modify columns by row
pull.

Pull out a single variable
add_count.

Add a count column to the data frame
mutate_across.

Mutate multiple columns simultaneously
pivot_wider.

Pivot data from long to wide
filter.

Filter rows on one or more conditions
coalesce.

Coalesce missing values
complete.

Complete a data.table with missing combinations of data
enframe.

Convert a vector to a data.table/tidytable
separate_rows.

Separate a collapsed column into multiple rows
first.

Extract the first, last, or nth value from a vector
new_tidytable

Create a tidytable from a list
nest_by.

Nest data.tables
case.

data.table::fcase() with vectorized default
%notin%

notin operator
if_all.

Create conditions on a selection of columns
ifelse.

Fast ifelse
get_dummies.

Convert character and factor columns to dummy variables
fread.

Read/write files
desc.

Descending order
slice.

Choose rows in a data.table
distinct.

Select distinct/unique rows
case_when.

Case when
drop_na.

Drop rows containing missing values
count.

Count observations by group
%>%

Pipe operator
pivot_longer.

Pivot data from wide to long
relocate.

Relocate a column to a new position
unnest.

Unnest list-columns
uncount.

Uncount a data.table
reexports

Objects exported from other packages
expand.

Expand a data.table to use all combinations of values
group_split.

Split data frame by groups
lags.

Get lagging or leading values
unite.

Unite multiple columns by pasting strings together
extract.

Extract a character column into multiple columns using regex
expand_grid.

Create a data.table from all combinations of inputs
map.

Apply a function to each element of a vector or list
mutate.

Add/modify/delete columns
na_if.

Convert values to NA
unnest_longer.

Unnest a list-column of vectors into regular columns
n.

Number of observations in each group
left_join.

Join two data.tables together
replace_na.

Replace missing values
n_distinct.

Count the number of unique values in a vector
separate.

Separate a character column into multiple columns
nest.

Nest data.tables
select.

Select or drop columns
row_number.

Return row number
summarize.

Aggregate data using summary statistics
summarize_across.

Summarize multiple columns
fill.

Fill in missing values with previous or next value
transmute.

Add new variables and drop all others
top_n.

Select top (or bottom) n rows (by value)
is_tidytable

Test if the object is a tidytable
inv_gc

Run invisible garbage collection
rename_with.

Rename multiple columns
tidytable

Build a data.table/tidytable
tidytable-vctrs

Internal vctrs methods
rename.

Rename variables by name
unnest_wider.

Unnest a list-column of vectors into a wide data frame
as_tidytable

Coerce an object to a data.table/tidytable
arrange.

Arrange/reorder rows
between.

Do the values from x fall between the left and right bounds?