require(data.table)
knitr::opts_chunk$set(
  comment = "#",
    error = FALSE,
     tidy = FALSE,
    cache = FALSE,
 collapse = TRUE
)
.old.th = setDTthreads(1)

This vignette introduces the data.table syntax, its general form, how to subset rows, select and compute on columns, and perform aggregations by group. Familiarity with the data.frame data structure from base R is useful, but not essential to follow this vignette.


Data analysis using data.table

Data manipulation operations such as subset, group, update, join, etc. are all inherently related. Keeping these related operations together allows for:

Briefly, if you are interested in reducing programming and compute time tremendously, then this package is for you. The philosophy that data.table adheres to makes this possible. Our goal is to illustrate it through this series of vignettes.

Data {#data}

In this vignette, we will use NYC-flights14 data obtained from the flights package (available on GitHub only). It contains On-Time flights data from the Bureau of Transportation Statistics for all the flights that departed from New York City airports in 2014 (inspired by nycflights13). The data is available only for Jan-Oct'14.

We can use data.table's fast-and-friendly file reader fread to load flights directly as follows:

options(width = 100L)
input <- if (file.exists("flights14.csv")) {
   "flights14.csv"
} else {
  "https://raw.githubusercontent.com/Rdatatable/data.table/master/vignettes/flights14.csv"
}
flights <- fread(input)
flights
dim(flights)

Aside: fread accepts http and https URLs directly, as well as operating system commands such as sed and awk output. See ?fread for examples.

Introduction

In this vignette, we will

  1. Start with the basics - what is a data.table, its general form, how to subset rows, how to select and compute on columns;

  2. Then we will look at performing data aggregations by group

1. Basics {#basics-1}

a) What is data.table? {#what-is-datatable-1a}

data.table is an R package that provides an enhanced version of a data.frame, the standard data structure for storing data in base R. In the Data section above, we saw how to create a data.table using fread(), but alternatively we can also create one using the data.table() function. Here is an example:

DT = data.table(
  ID = c("b","b","b","a","a","c"),
  a = 1:6,
  b = 7:12,
  c = 13:18
)
DT
class(DT$ID)

You can also convert existing objects to a data.table using setDT() (for data.frame and list structures) or as.data.table() (for other structures). For more details pertaining to the difference (goes beyond the scope of this vignette), please see ?setDT and ?as.data.table.

Note that:

b) General form - in what way is a data.table enhanced? {#enhanced-1b}

In contrast to a data.frame, you can do a lot more than just subsetting rows and selecting columns within the frame of a data.table, i.e., within [ ... ] (NB: we might also refer to writing things inside DT[...] as "querying DT", as an analogy or in relevance to SQL). To understand it we will have to first look at the general form of the data.table syntax, as shown below:

DT[i, j, by]

##   R:                 i                 j        by
## SQL:  where | order by   select | update  group by

Users with an SQL background might perhaps immediately relate to this syntax.

The way to read it (out loud) is:

Take DT, subset/reorder rows using i, then calculate j, grouped by by.

Let's begin by looking at i and j first - subsetting rows and operating on columns.

c) Subset rows in i {#subset-i-1c}

-- Get all the flights with "JFK" as the origin airport in the month of June.

ans <- flights[origin == "JFK" & month == 6L]
head(ans)

-- Get the first two rows from flights. {#subset-rows-integer}

ans <- flights[1:2]
ans

-- Sort flights first by column origin in ascending order, and then by dest in descending order:

We can use the R function order() to accomplish this.

ans <- flights[order(origin, -dest)]
head(ans)

order() is internally optimised

We will discuss data.table's fast order in more detail in the data.table internals vignette.

d) Select column(s) in j {#select-j-1d}

-- Select arr_delay column, but return it as a vector.

ans <- flights[, arr_delay]
head(ans)

-- Select arr_delay column, but return as a data.table instead.

ans <- flights[, list(arr_delay)]
head(ans)

A data.table (and a data.frame too) is internally a list as well, with the stipulation that each element has the same length and the list has a class attribute. Allowing j to return a list enables converting and returning data.table very efficiently.

Tip: {#tip-1}

As long as j-expression returns a list, each element of the list will be converted to a column in the resulting data.table. This makes j quite powerful, as we will see shortly. It is also very important to understand this for when you'd like to make more complicated queries!!

-- Select both arr_delay and dep_delay columns.

ans <- flights[, .(arr_delay, dep_delay)]
head(ans)

## alternatively
# ans <- flights[, list(arr_delay, dep_delay)]

-- Select both arr_delay and dep_delay columns and rename them to delay_arr and delay_dep.

Since .() is just an alias for list(), we can name columns as we would while creating a list.

ans <- flights[, .(delay_arr = arr_delay, delay_dep = dep_delay)]
head(ans)

e) Compute or do in j

-- How many trips have had total delay < 0?

ans <- flights[, sum( (arr_delay + dep_delay) < 0 )]
ans

What's happening here?

f) Subset in i and do in j

-- Calculate the average arrival and departure delay for all flights with "JFK" as the origin airport in the month of June.

ans <- flights[origin == "JFK" & month == 6L,
               .(m_arr = mean(arr_delay), m_dep = mean(dep_delay))]
ans

Because the three main components of the query (i, j and by) are together inside [...], data.table can see all three and optimise the query altogether before evaluation, rather than optimizing each separately. We are able to therefore avoid the entire subset (i.e., subsetting the columns besides arr_delay and dep_delay), for both speed and memory efficiency.

-- How many trips have been made in 2014 from "JFK" airport in the month of June?

ans <- flights[origin == "JFK" & month == 6L, length(dest)]
ans

The function length() requires an input argument. We just need to compute the number of rows in the subset. We could have used any other column as the input argument to length(). This approach is reminiscent of SELECT COUNT(dest) FROM flights WHERE origin = 'JFK' AND month = 6 in SQL.

This type of operation occurs quite frequently, especially while grouping (as we will see in the next section), to the point where data.table provides a special symbol .N for it.

Special symbol .N: {#special-N}

.N is a special built-in variable that holds the number of observations in the current group. It is particularly useful when combined with by as we'll see in the next section. In the absence of group by operations, it simply returns the number of rows in the subset.

Now that we now, we can now accomplish the same task by using .N as follows:

ans <- flights[origin == "JFK" & month == 6L, .N]
ans

We could have accomplished the same operation by doing nrow(flights[origin == "JFK" & month == 6L]). However, it would have to subset the entire data.table first corresponding to the row indices in i and then return the rows using nrow(), which is unnecessary and inefficient. We will cover this and other optimisation aspects in detail under the data.table design vignette.

g) Great! But how can I refer to columns by names in j (like in a data.frame)? {#refer_j}

If you're writing out the column names explicitly, there's no difference compared to a data.frame (since v1.9.8).

-- Select both arr_delay and dep_delay columns the data.frame way.

ans <- flights[, c("arr_delay", "dep_delay")]
head(ans)

If you've stored the desired columns in a character vector, there are two options: Using the .. prefix, or using the with argument.

-- Select columns named in a variable using the .. prefix

select_cols = c("arr_delay", "dep_delay")
flights[ , ..select_cols]

For those familiar with the Unix terminal, the .. prefix should be reminiscent of the "up-one-level" command, which is analogous to what's happening here -- the .. signals to data.table to look for the select_cols variable "up-one-level", i.e., within the global environment in this case.

-- Select columns named in a variable using with = FALSE

flights[ , select_cols, with = FALSE]

The argument is named with after the R function with() because of similar functionality. Suppose you have a data.frame DF and you'd like to subset all rows where x > 1. In base R you can do the following:

DF = data.frame(x = c(1,1,1,2,2,3,3,3), y = 1:8)

## (1) normal way
DF[DF$x > 1, ] # data.frame needs that ',' as well

## (2) using with
DF[with(DF, x > 1), ]

with = TRUE is the default in data.table because we can do much more by allowing j to handle expressions - especially when combined with by, as we'll see in a moment.

2. Aggregations

We've already seen i and j from data.table's general form in the previous section. In this section, we'll see how they can be combined together with by to perform operations by group. Let's look at some examples.

a) Grouping using by

-- How can we get the number of trips corresponding to each origin airport?

ans <- flights[, .(.N), by = .(origin)]
ans

## or equivalently using a character vector in 'by'
# ans <- flights[, .(.N), by = "origin"]

-- How can we calculate the number of trips for each origin airport for carrier code "AA"? {#origin-.N}

The unique carrier code "AA" corresponds to American Airlines Inc.

ans <- flights[carrier == "AA", .N, by = origin]
ans

-- How can we get the total number of trips for each origin, dest pair for carrier code "AA"? {#origin-dest-.N}

ans <- flights[carrier == "AA", .N, by = .(origin, dest)]
head(ans)

## or equivalently using a character vector in 'by'
# ans <- flights[carrier == "AA", .N, by = c("origin", "dest")]

-- How can we get the average arrival and departure delay for each orig,dest pair for each month for carrier code "AA"? {#origin-dest-month}

ans <- flights[carrier == "AA",
        .(mean(arr_delay), mean(dep_delay)),
        by = .(origin, dest, month)]
ans

Now what if we would like to order the result by those grouping columns origin, dest and month?

b) Sorted by: keyby

data.table retaining the original order of groups is intentional and by design. There are cases when preserving the original order is essential. But at times we would like to automatically sort by the variables in our grouping.

-- So how can we directly order by all the grouping variables?

ans <- flights[carrier == "AA",
        .(mean(arr_delay), mean(dep_delay)),
        keyby = .(origin, dest, month)]
ans

Keys: Actually keyby does a little more than just ordering. It also sets a key after ordering by setting an attribute called sorted.

We'll learn more about keys in the Keys and fast binary search based subset vignette; for now, all you have to know is that you can use keyby to automatically order the result by the columns specified in by.

c) Chaining

Let's reconsider the task of getting the total number of trips for each origin, dest pair for carrier "AA".

ans <- flights[carrier == "AA", .N, by = .(origin, dest)]

-- How can we order ans using the columns origin in ascending order, and dest in descending order?

We can store the intermediate result in a variable, and then use order(origin, -dest) on that variable. It seems fairly straightforward.

ans <- ans[order(origin, -dest)]
head(ans)

But this requires having to assign the intermediate result and then overwriting that result. We can do one better and avoid this intermediate assignment to a temporary variable altogether by chaining expressions.

ans <- flights[carrier == "AA", .N, by = .(origin, dest)][order(origin, -dest)]
head(ans, 10)

d) Expressions in by

-- Can by accept expressions as well or does it just take columns?

Yes it does. As an example, if we would like to find out how many flights started late but arrived early (or on time), started and arrived late etc...

ans <- flights[, .N, .(dep_delay>0, arr_delay>0)]
ans

e) Multiple columns in j - .SD

-- Do we have to compute mean() for each column individually?

It is of course not practical to have to type mean(myCol) for every column one by one. What if you had 100 columns to average mean()?

How can we do this efficiently and concisely? To get there, refresh on this tip - "As long as the j-expression returns a list, each element of the list will be converted to a column in the resulting data.table". If we can refer to the data subset for each group as a variable while grouping, we can then loop through all the columns of that variable using the already- or soon-to-be-familiar base function lapply(). No new names to learn specific to data.table.

Special symbol .SD: {#special-SD}

data.table provides a special symbol called .SD. It stands for Subset of Data. It by itself is a data.table that holds the data for the current group defined using by.

Recall that a data.table is internally a list as well with all its columns of equal length.

Let's use the data.table DT from before to get a glimpse of what .SD looks like.

DT

DT[, print(.SD), by = ID]

To compute on (multiple) columns, we can then simply use the base R function lapply().

DT[, lapply(.SD, mean), by = ID]

We are almost there. There is one little thing left to address. In our flights data.table, we only wanted to calculate the mean() of the two columns arr_delay and dep_delay. But .SD would contain all the columns other than the grouping variables by default.

-- How can we specify just the columns we would like to compute the mean() on?

.SDcols

Using the argument .SDcols. It accepts either column names or column indices. For example, .SDcols = c("arr_delay", "dep_delay") ensures that .SD contains only these two columns for each group.

Similar to part g), you can also specify the columns to remove instead of columns to keep using - or !. Additionally, you can select consecutive columns as colA:colB and deselect them as !(colA:colB) or -(colA:colB).

Now let us try to use .SD along with .SDcols to get the mean() of arr_delay and dep_delay columns grouped by origin, dest and month.

flights[carrier == "AA",                       ## Only on trips with carrier "AA"
        lapply(.SD, mean),                     ## compute the mean
        by = .(origin, dest, month),           ## for every 'origin,dest,month'
        .SDcols = c("arr_delay", "dep_delay")] ## for just those specified in .SDcols

f) Subset .SD for each group:

-- How can we return the first two rows for each month?

ans <- flights[, head(.SD, 2), by = month]
head(ans)

g) Why keep j so flexible?

So that we have a consistent syntax and keep using already existing (and familiar) base functions instead of learning new functions. To illustrate, let us use the data.table DT that we created at the very beginning under the section What is a data.table?.

-- How can we concatenate columns a and b for each group in ID?

DT[, .(val = c(a,b)), by = ID]

-- What if we would like to have all the values of column a and b concatenated, but returned as a list column?

DT[, .(val = list(c(a,b))), by = ID]

Once you start internalising usage in j, you will realise how powerful the syntax can be. A very useful way to understand it is by playing around, with the help of print().

For example:

## look at the difference between
DT[, print(c(a,b)), by = ID] # (1)

## and
DT[, print(list(c(a,b))), by = ID] # (2)

In (1), for each group, a vector is returned, with length = 6,4,2 here. However, (2) returns a list of length 1 for each group, with its first element holding vectors of length 6,4,2. Therefore, (1) results in a length of 6+4+2 =r 6+4+2, whereas (2) returns `1+1+1=`r 1+1+1.

Summary

The general form of data.table syntax is:

DT[i, j, by]

We have seen so far that,

Using i:

We can do much more in i by keying a data.table, which allows for blazing fast subsets and joins. We will see this in the "Keys and fast binary search based subsets" and "Joins and rolling joins" vignette.

Using j:

  1. Select columns the data.table way: DT[, .(colA, colB)].

  2. Select columns the data.frame way: DT[, c("colA", "colB")].

  3. Compute on columns: DT[, .(sum(colA), mean(colB))].

  4. Provide names if necessary: DT[, .(sA =sum(colA), mB = mean(colB))].

  5. Combine with i: DT[colA > value, sum(colB)].

Using by:

And remember the tip:

As long as j returns a list, each element of the list will become a column in the resulting data.table.

We will see how to add/update/delete columns by reference and how to combine them with i and by in the next vignette.


setDTthreads(.old.th)


Rdatatable/data.table documentation built on April 17, 2024, 9:02 p.m.