ZetCode

R data.table

last modified November 19, 2026

data.table is a package that implements a table as a data frame with extra speed and a very compact syntax. A single pair of brackets carries three selectors: i chooses rows, j chooses or computes columns, and by groups the result. The package also updates columns by reference, which means that an assignment changes the table in place instead of copying it. This article introduces the bracket syntax, grouped aggregation, reference updates, keys, and the fast file reader that makes data.table a common choice for large data sets. The examples use data.table 1.18.6.1 with R 4.5.2.

The examples need the data.table package, which is not part of base R. Install it once with install.packages("data.table"); the installing packages section of the introduction explains the details.

Creating a data.table

The constructor takes the same column vectors as data.frame and returns an object with class data.table and data.frame. A data.table prints with the row number followed by a colon, and the column types appear under the names, as in a tibble.

create.R
library(data.table)
students <- data.table(
  name = c("Ada", "Grace", "Alan"),
  score = c(90, 85, 66)
)
print(students)
cat("class:", class(students), "\n")

The class vector confirms that a data.table can be passed to any function that expects a data frame. The printout shows the types <char> and <num>, and the 1: prefix marks the row numbers. A data.table prints up to one hundred rows by default, which is more than a tibble shows; the limit is controlled by options for larger tables.

$ Rscript create.R
     name score
   <char> <num>
1:    Ada    90
2:  Grace    85
3:   Alan    66
class: data.table data.frame 

Filtering rows with i

The first position inside the brackets is i, the row selector. It accepts a logical condition, a vector of positions, or an expression that evaluates to either. A data.table evaluates the condition inside the table, so the column names are written without a prefix.

i.R
library(data.table)
students <- data.table(
  name = c("Ada", "Grace", "Alan", "Edsger"),
  score = c(90, 85, 66, 78)
)
print(students[score >= 80])
print(students[1:2])

The first call keeps the two students with at least 80 points. The second keeps the first two rows by position. The comma after i is required even when no column selector follows, because the three selectors are positional: leaving out the comma would make the expression a column selector instead.

$ Rscript i.R
     name score
   <char> <num>
1:    Ada    90
2:  Grace    85
     name score
   <char> <num>
1:    Ada    90
2:  Grace    85

Selecting and computing with j

The second position is j, the column selector. A list of columns is written with .(), which is shorthand for list(). A single expression that returns one value produces a one-value result, and a named list produces a table with the given column names.

j.R
library(data.table)
students <- data.table(
  name = c("Ada", "Grace", "Alan", "Edsger"),
  score = c(90, 85, 66, 78)
)
print(students[, .(name, score)])
print(students[, mean(score)])
print(students[, .(avg = mean(score), best = max(score))])

The first call returns the name and score columns as a data.table. The second returns the mean as a single number, and the third returns a one-row table with two named columns. A bare column name in j is an expression that returns a vector, so DT[, score] returns a vector, while DT[, .(score)] returns a table.

$ Rscript j.R
     name score
   <char> <num>
1:    Ada    90
2:  Grace    85
3:   Alan    66
4: Edsger    78
[1] 79.75
     avg  best
   <num> <num>
1: 79.75    90

Grouping with by

The by argument splits the rows into groups before j is evaluated. The special symbol .N is the number of rows in the current group, so .N alone counts the rows and .N inside a list adds a count column to a summary.

group-by.R
library(data.table)
students <- data.table(
  name = c("Ada", "Grace", "Alan", "Edsger", "Barbara", "Donald"),
  score = c(90, 85, 66, 78, 95, 71),
  subject = c("math", "art", "math", "art", "math", "art")
)
print(students[, .(avg = mean(score), n = .N), by = subject])
print(students[, .N, by = subject])

Mathematics averages 83.67 and art averages 78, with three students in each group. The groups appear in the order in which their first row occurs in the table, not in alphabetical order. by accepts several columns, which produces one row per combination of their values.

$ Rscript group-by.R
   subject      avg     n
    <char>    <num> <int>
1:    math 83.66667     3
2:     art 78.00000     3
   subject     N
    <char> <int>
1:    math     3
2:     art     3

Updating by reference

The operator := adds or replaces a column in place. No assignment to the variable is needed, and no copy is made, which is what makes the operation fast on large tables. The same operator with NULL on the right removes a column.

update-ref.R
library(data.table)
students <- data.table(
  name = c("Ada", "Grace", "Alan"),
  score = c(90, 85, 66)
)
students[, passed := score >= 70]
students[, score := score + 5]
print(students)
students[, c("passed", "score") := NULL]
print(students)

The first statement adds passed, the second adds five points to every score, and the third removes both columns. Because the table is changed in place, any other variable that points to the same object sees the change as well. When the original must be preserved, call copy(DT) first and modify the copy.

$ Rscript update-ref.R
     name score passed
   <char> <num> <lgcl>
1:    Ada    95   TRUE
2:  Grace    90   TRUE
3:   Alan    71  FALSE
     name
   <char>
1:    Ada
2:  Grace
3:   Alan

Keys and ordering

setkey sorts a table by a column and marks that column as its key. A key enables fast lookups: DT[.(2)] finds the rows whose key equals 2 without scanning the table. setorder sorts by any columns without creating a key.

keys.R
library(data.table)
students <- data.table(
  id = c(3, 1, 2),
  name = c("Alan", "Ada", "Grace")
)
setkey(students, id)
print(students)
print(students[.(2)])
setorder(students, -id)
print(students)

After setkey, the table is ordered by id and the printout starts with a Key: <id> line. DT[.(2)] returns Grace alone, and setorder(students, -id) reverses the order without setting a key. A key is worth setting when the same table is looked up repeatedly; for a single scan, a condition in i is just as clear.

$ Rscript keys.R
Key: <id>
      id   name
   <num> <char>
1:     1    Ada
2:     2  Grace
3:     3   Alan
Key: <id>
      id   name
   <num> <char>
1:     2  Grace
      id   name
   <num> <char>
1:     3   Alan
2:     2  Grace
3:     1    Ada

Reading and writing files

fread reads a delimited file and guesses the column types, and fwrite writes a data.table back to disk. Both are considerably faster than the base functions and handle large files without loading the whole text into memory as a character vector.

fread-fwrite.R
library(data.table)
students <- data.table(
  name = c("Ada", "Grace", "Alan"),
  score = c(90, 85, 66)
)
fwrite(students, "students.csv")
back <- fread("students.csv")
print(back)
cat("rows:", nrow(back), "\n")

The file round-trips with the same values, but the score column comes back as an integer because the written values have no decimal part. Type guessing is usually correct for clean files and can be overridden with colClasses when a column such as a postal code must stay character. The argument data.table = FALSE makes fread return a plain data frame instead.

$ Rscript fread-fwrite.R
     name score
   <char> <int>
1:    Ada    90
2:  Grace    85
3:   Alan    66
rows: 3 

A complete example

The next script adds a passed column, keeps the passing rows, and summarises each subject in one chained expression. The first bracket computes the summary, and the second bracket orders the result by average, which is the data.table equivalent of a pipeline.

report.R
library(data.table)
students <- data.table(
  name = c("Ada", "Grace", "Alan", "Edsger", "Barbara", "Donald"),
  score = c(90, 85, 66, 78, 95, 71),
  hours = c(12, 10, 8, 11, 14, 9),
  subject = c("math", "art", "math", "art", "math", "art")
)
students[, passed := score >= 70]
result <- students[passed == TRUE,
  .(avg = mean(score), best = max(score), n = .N),
  by = subject][order(-avg)]
print(result)

Mathematics leads with an average of 92.5 from two students, and art follows with 78 from three. Donald's 71 is below the threshold, so he is removed before the averages are computed. The order of the two brackets matters: filtering first changes both the groups and the counts, while ordering first would only change the row order of the final table.

$ Rscript report.R
   subject   avg  best     n
    <char> <num> <num> <int>
1:    math  92.5    95     2
2:     art  78.0    85     3

Next steps

The dplyr article solves the same problems with named verbs and copies, and the tidyr article reshapes tables in the tidyverse style. The data frames article covers the base class that both packages extend, and the descriptive statistics article explains the summaries computed here.

Source

data.table vignette: introduction

data.table reference: the data.table class

data.table reference: setkey and setorder

data.table reference: fread and fwrite

In this article we have created a data.table and used the three selectors i, j, and by. We filtered rows, selected and computed columns with .(), counted groups with .N, and updated columns by reference with :=. We set keys, looked up rows with .(value), sorted with setorder, and read and wrote a CSV file with fread and fwrite. The final example chained two brackets into a grouped report. The series continues with R descriptive statistics.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all R Language tutorials.