tibble and the pipe: short forms worth knowing
Contents
The idiom in one line
This is the shape worth internalising: build the data, transform it,
hand it to ggplot, and never create an intermediate
object.
tibble(b = seq(-3, 3, length.out = 200)) |>
mutate(density = dnorm(b), cumulative = pnorm(b)) |>
ggplot(aes(b, density)) +
geom_area(fill = pal[["blue"]], alpha = 0.2) +
geom_line(colour = pal[["blue"]], linewidth = 1) +
labs(title = "Data in, plot out, nothing left behind",
x = expression(beta), y = "density")

Three things are happening, and the rest of this post is about each
of them: tibble() builds a data frame whose columns can
refer to one another, |> passes the result along without
naming it, and + takes over the moment
ggplot() is reached.
Why tibble instead of data.frame
A tibble is a data frame – it inherits from
data.frame, so anything that accepts one accepts a tibble.
What differs is a set of defaults chosen to fail loudly rather than
guess.
tb <- tibble(patient = 1:3,
arm = c("control", "treatment", "control"),
days = c(412, 88, 1003),
dead = c(TRUE, FALSE, TRUE))
tb
## # A tibble: 3 × 4
## patient arm days dead
## <int> <chr> <dbl> <lgl>
## 1 1 control 412 TRUE
## 2 2 treatment 88 FALSE
## 3 3 control 1003 TRUE
The header tells you the dimensions and every column’s type:
<int>, <chr>,
<dbl>, <lgl>. With a data frame
you would run str() to learn the same thing, and
str() on a wide data frame is a wall of text.
data.frame(patient = 1:3,
arm = c("control", "treatment", "control"))
## patient arm
## 1 1 control
## 2 2 treatment
## 3 3 control
No types, no dimensions. Fine for three rows; less fine when a character column you believed was numeric silently fails to be.
A tibble also prints only the first 10 rows, so typing its name is always safe. To see more, ask:
tibble(i = 1:100, sq = i^2) |> print(n = 3)
## # A tibble: 100 × 2
## i sq
## <int> <dbl>
## 1 1 1
## 2 2 4
## 3 3 9
## # ℹ 97 more rows
Three ways to make one
tibble() – column by column, the usual
case.
tibble(x = 1:3, y = c("a", "b", "c"))
## # A tibble: 3 × 2
## x y
## <int> <chr>
## 1 1 a
## 2 2 b
## 3 3 c
tribble() – row by row, for small
literal tables. The layout on screen matches the layout of the data,
which makes transcription errors visible.
tribble(
~term, ~hazard_ratio, ~lower, ~upper,
"sex", 0.54, 0.38, 0.77,
"ecog", 2.07, 1.41, 3.04,
"age", 0.93, 0.59, 1.49)
## # A tibble: 3 × 4
## term hazard_ratio lower upper
## <chr> <dbl> <dbl> <dbl>
## 1 sex 0.54 0.38 0.77
## 2 ecog 2.07 1.41 3.04
## 3 age 0.93 0.59 1.49
as_tibble() – convert something that
already exists. Note the rownames argument: tibbles have no
row names, so a matrix or a data frame that carries meaning in its row
names needs that information moved into a real column, or it is
lost.
as_tibble(head(mtcars, 3), rownames = "car")[, 1:4]
## # A tibble: 3 × 4
## car mpg cyl disp
## <chr> <dbl> <dbl> <dbl>
## 1 Mazda RX4 21 6 160
## 2 Mazda RX4 Wag 21 6 160
## 3 Datsun 710 22.8 4 108
This comes up constantly with model output, which is usually a matrix with informative row names:
m <- lm(mpg ~ wt + hp, data = mtcars)
as_tibble(summary(m)$coefficients, rownames = "term")
## # A tibble: 3 × 5
## term Estimate `Std. Error` `t value` `Pr(>|t|)`
## <chr> <dbl> <dbl> <dbl> <dbl>
## 1 (Intercept) 37.2 1.60 23.3 2.57e-20
## 2 wt -3.88 0.633 -6.13 1.12e- 6
## 3 hp -0.0318 0.00903 -3.52 1.45e- 3
Without rownames = "term" you would have a table of
numbers with no way to tell which is the intercept.
Sequential evaluation: the feature and the trap
Inside tibble(), each column is evaluated in order and
can refer to columns already defined. data.frame() cannot
do this.
tibble(x = 1:4, doubled = x * 2, total = x + doubled)
## # A tibble: 4 × 3
## x doubled total
## <int> <dbl> <dbl>
## 1 1 2 3
## 2 2 4 6
## 3 3 6 9
## 4 4 8 12
try(data.frame(x = 1:4, doubled = x * 2))
## Error in eval(expr, envir) : object 'x' not found
That is genuinely useful – it removes a whole class of
mutate() calls. It also sets a trap, and it is one I have
walked into on this blog. Suppose you want the start and end of each
segment in a path:
px <- c(10, 20, 30, 40)
try(tibble(x = px[-length(px)],
xend = x[-1])) # `x` here is the COLUMN just created
## Error in tibble(x = px[-length(px)], xend = x[-1]) :
## Tibble columns must have compatible sizes.
## • Size 3: Existing data.
## • Size 2: Column `xend`.
## ℹ Only values of size one are recycled.
x inside the call refers to the new column, not to
px. The column has 3 elements, x[-1] has 2,
and the sizes no longer agree. Refer to the source vector instead:
tibble(x = px[-length(px)],
xend = px[-1])
## # A tibble: 3 × 2
## x xend
## <dbl> <dbl>
## 1 10 20
## 2 20 30
## 3 30 40
The rule: once a name exists as a column, it shadows anything of that
name outside. Name your inputs distinctly (px,
py) and the ambiguity disappears.
Stricter on purpose
Recycling. A data frame recycles any length that divides evenly. A tibble recycles only length 1.
data.frame(a = 1:4, b = 1:2) # silently repeats b
## a b
## 1 1 1
## 2 2 2
## 3 3 1
## 4 4 2
try(tibble(a = 1:4, b = 1:2))
## Error in tibble(a = 1:4, b = 1:2) :
## Tibble columns must have compatible sizes.
## • Size 4: Existing data.
## • Size 2: Column `b`.
## ℹ Only values of size one are recycled.
tibble(a = 1:4, b = 0) # length 1 is fine
## # A tibble: 4 × 2
## a b
## <int> <dbl>
## 1 1 0
## 2 2 0
## 3 3 0
## 4 4 0
Recycling a length-2 vector into 4 rows is almost always a bug. The data frame does it quietly; the tibble stops.
Names are left alone.
c(data.frame = names(data.frame(`my col` = 1, check.names = TRUE)),
tibble = names(tibble(`my col` = 1)))
## data.frame tibble
## "my.col" "my col"
No partial matching.
df <- data.frame(value = 1:3)
tb <- tibble(value = 1:3)
# list(), not c(): c() would drop the NULL and recycle the names
list(data.frame = df$val, # silently matches `value`
tibble = tb$val) # NULL, with a warning
## $data.frame
## [1] 1 2 3
##
## $tibble
## NULL
[ never drops to a vector.
c(df_bracket = class(df[, 1]),
tbl_bracket = class(tb[, 1])[1],
tbl_dbl = class(tb[[1]]))
## df_bracket tbl_bracket tbl_dbl
## "integer" "tbl_df" "integer"
df[, 1] returning a vector is the classic source of
functions that work on multi-column input and break on single-column
input. With a tibble, [ always gives a tibble and
[[ always gives the vector – you choose, explicitly.
List columns
A tibble column can hold a list, which means it can hold anything – vectors of different lengths, models, even plots. This is what makes split-apply workflows possible without leaving the data frame.
nested <- tibble(cyl = c(4, 6, 8)) |>
mutate(data = lapply(cyl, \(k) mtcars[mtcars$cyl == k, ]),
n = sapply(data, nrow),
model = lapply(data, \(d) lm(mpg ~ wt, data = d)),
slope = sapply(model, \(m) coef(m)[["wt"]]))
nested |> select(cyl, n, slope)
## # A tibble: 3 × 3
## cyl n slope
## <dbl> <int> <dbl>
## 1 4 11 -5.65
## 2 6 7 -2.78
## 3 8 14 -2.19
nested
## # A tibble: 3 × 5
## cyl data n model slope
## <dbl> <list> <int> <list> <dbl>
## 1 4 <df [11 × 11]> 11 <lm> -5.65
## 2 6 <df [7 × 11]> 7 <lm> -2.78
## 3 8 <df [14 × 11]> 14 <lm> -2.19
Three models, fitted and stored in a column, with their slopes
alongside. <list> and <lm> in the
header are the giveaway that these are not ordinary atomic columns.
When a tibble bites
A short list of the things that actually go wrong.
Old code that expects [ to drop.
Anything written against base data frames that does
x[, 1] + 1 will fail. Fix with x[[1]] or
as.data.frame(x).
Functions that need row names. Some base and older
modelling functions read row names. as_tibble() discards
them silently, so capture them first with
rownames = "...".
Matrices. A tibble is a list of columns, not a
matrix. If you need matrix algebra, as.matrix() first – and
remember that a character column will coerce the whole matrix to
character.
as.matrix(tibble(a = 1:2, b = c("x", "y")))
## a b
## [1,] "1" "x"
## [2,] "2" "y"
Every number is now a string. This is a base R rule, not a tibble rule, but mixed-type tibbles make it easy to hit.
Printing hides things. Only 10 rows and only the
columns that fit. Use print(n = Inf, width = Inf) when you
need to see everything.
|> versus %>%
%>% came from magrittr in 2014 and
arrives with dplyr. |> is base R, added
in 4.1, and needs no package at all.
The crucial difference is what they are. |> is pure
syntax: R rewrites it while parsing, before anything runs.
quote(x |> f(y))
## f(x, y)
identical(quote(x |> f(y)), quote(f(x, y)))
## [1] TRUE
The pipe has vanished – there is no |> left in the
parsed expression. %>% is an ordinary function, and
stays one:
quote(x %>% f(y))
## x %>% f(y)
That is why |> costs nothing and %>%
costs a little:
x <- 1:100
f <- function(v) v + 1L
N <- 1e5
timings <- c(
`f(x)` = system.time(for (i in seq_len(N)) f(x))[["elapsed"]],
`x |> f()` = system.time(for (i in seq_len(N)) x |> f())[["elapsed"]],
`x %>% f()` = system.time(for (i in seq_len(N)) x %>% f())[["elapsed"]])
round(1e6 * timings / N, 2) # microseconds per call
## f(x) x |> f() x %>% f()
## 0.28 0.27 0.96
tibble(form = names(timings), us = 1e6 * timings / N) |>
mutate(form = factor(form, levels = names(timings))) |>
ggplot(aes(us, form)) +
geom_col(aes(fill = form), width = 0.6, show.legend = FALSE) +
scale_fill_manual(values = unname(pal[c("grey", "blue", "magenta")])) +
labs(title = "Per-call cost of the two pipes",
subtitle = "the native pipe is indistinguishable from a direct call",
x = "microseconds per call", y = NULL)

Keep the scale in mind: the difference is well under a microsecond. It matters inside a loop running millions of times and nowhere else. Correctness and readability should decide this, not speed.
The placeholder
Both pipes put the left side into the first argument. When you need it somewhere else, you need a placeholder – and here the two differ sharply.
magrittr uses ., anywhere, as often as you like:
3 %>% seq(1, .) %>% rep(2)
## [1] 1 2 3 1 2 3
Base R uses _, and it must be a named
argument:
c(1, 2) |> setdiff(x = c(1, 2, 3), y = _)
## [1] 3
Misusing _ is a syntax error, raised
while R is parsing, before a single line runs. That is a real advantage
– the mistake cannot reach production – but it also means
try() cannot catch it, and a bad _ will stop
an .Rmd from knitting at all. To show the messages here,
the code has to be parsed at run time from a string:
syntax_error <- function(code) {
tryCatch({ eval(parse(text = code)); "no error" },
error = function(e) conditionMessage(e))
}
syntax_error("c(3, 1, 2) |> sort(_)") # not a named argument
## [1] "pipe placeholder can only be used as a named argument (<input>:1:15)"
It may also appear only once per call:
syntax_error("3 |> seq(1, _) |> rep(_)")
## [1] "pipe placeholder can only be used as a named argument (<input>:1:6)"
Since R 4.3 the placeholder does work with extraction, which covers the most common need:
mtcars |> _$mpg |> head(3)
## [1] 21.0 21.0 22.8
When _ will not do, an anonymous function always
will:
c(3, 1, 2) |> (\(v) sort(v, decreasing = TRUE))()
## [1] 3 2 1
The differences that matter
|> (base) |
%>% (magrittr) |
|
|---|---|---|
| Needs a package | no | yes |
| Runtime cost | none | small but real |
| Right side may be a bare name | no, x \|> sum errors |
yes, x %>% sum works |
| Placeholder | _, named arguments only, once |
., anywhere, repeatable |
| Builds reusable pipelines | no | yes, . %>% f() %>% g() |
| Works in older R | 4.1+ | any |
syntax_error("1:3 |> sum") # again a parse error, not a runtime one
## [1] "The pipe operator requires a function call as RHS (<input>:1:8)"
1:3 %>% sum # magrittr accepts a bare function name
## [1] 6
The functional-sequence trick is magrittr’s one genuinely unique capability:
standardise <- . %>% abs() %>% sqrt()
standardise(c(-16, -81))
## [1] 4 9
Other infix operators you will meet
Anything wrapped in %...% is an infix operator, and most
of them have nothing to do with piping.
list(`5 %in% c(1,5)` = 5 %in% c(1, 5), # membership (logical)
`7 %% 3` = 7 %% 3, # remainder
`7 %/% 3` = 7 %/% 3) # integer division
## $`5 %in% c(1,5)`
## [1] TRUE
##
## $`7 %% 3`
## [1] 1
##
## $`7 %/% 3`
## [1] 2
%||% returns the left side unless it is
NULL. It lived in rlang for years and is now in base R,
which is worth knowing because older advice says to import it.
list(in_base_R = exists("%||%", envir = baseenv()),
result = NULL %||% 42,
unchanged = 7 %||% 42)
## $in_base_R
## [1] TRUE
##
## $result
## [1] 42
##
## $unchanged
## [1] 7
magrittr adds two more. %$% exposes the columns of a
data frame as names, and %T>% (“tee”) passes the
left side onward so you can slip a side effect into a
pipeline:
mtcars %$% cor(mpg, wt)
## [1] -0.8676594
c(4, 9, 16) %T>% {cat("n =", length(.), "\n")} %>% sqrt()
## n = 3
## [1] 2 3 4
And you can define your own:
`%+-%` <- function(estimate, margin) c(estimate - margin, estimate + margin)
1.96 %+-% 0.5
## [1] 1.46 2.46
Why ggplot2 uses + and not a pipe
ggplot2 is older than magrittr, so + was never a
stylistic choice – there was nothing else. But it is also the right
operator, for a reason worth understanding.
A pipe puts the left side into the first argument.
ggplot()’s first argument is data. So piping a
plot into a layer would try to use the plot as data:
p <- ggplot(mtcars, aes(wt, mpg))
try(p |> geom_point())
## Error in geom_point(p) : `mapping` must be created by `aes()`.
## ✖ You've supplied a <ggplot2::ggplot> object.
## ℹ Did you use `%>%` or `|>` instead of `+`?
+ does something different: ggplot2 defines
a method for it that adds a layer to an existing plot object.
The two operators are not interchangeable because they mean different
things – one substitutes an argument, the other combines two
objects.
Hence the idiom from the top of this post: pipe while you are
handling data, switch to + the moment you
reach ggplot(), and never switch back.
mtcars |>
filter(cyl %in% c(4, 8)) |>
mutate(cylinders = factor(cyl)) |>
ggplot(aes(wt, mpg, colour = cylinders)) +
geom_point(size = 2.5, alpha = 0.8) +
geom_smooth(method = "lm", se = FALSE, linewidth = 0.8) +
scale_colour_manual(values = unname(pal[c("blue", "orange")])) +
labs(title = "Pipe the data, add the layers",
x = "weight (1000 lbs)", y = "miles per gallon")

A useful tell when reading someone else’s code: everything before
ggplot() is data manipulation, everything after it is
appearance.
Which to use
Use |>. It needs no package, it
costs nothing, it is one character shorter, and code written with it
runs for anyone on R 4.1 or later even without the tidyverse installed.
For the overwhelmingly common case –
data |> verb() |> verb() – the two are
interchangeable, and the base one has fewer dependencies.
Reach for %>% when you need the
placeholder in an awkward position, when you want a reusable functional
sequence, or when you are maintaining code that already uses it. Mixing
both in one file is legal but reads badly; pick one per project.
For tibbles, the defaults are the point. Loud failure on bad recycling, no partial matching, no silent dropping to vectors, and types visible on every print. Each of those turns a bug you would have found later into an error you find now.
References
- Wickham H, Çetinkaya-Rundel M, Grolemund G. R for Data Science, 2nd ed. – chapters on data transformation and workflow.
- tibble.tidyverse.org and
vignette("tibble"). - magrittr.tidyverse.org
for
%>%,%$%,%T>%. - R Core Team. NEWS
for R 4.1.0 – introduction of
|>; 4.2.0 added_, 4.3.0 extended it to extraction.