Tibbles
Prerequisites: Importing and exporting data
A tibble is the tidyverse's modern version of a data frame. It is a data frame — every data-frame function works on it — with a few changes that make it friendlier.
library(tibble)
people <- tibble(
name = c("Ada", "Linus", "Grace"),
age = c(36, 28, 45),
age_months = age * 12
)
people
# A tibble: 3 × 3
name age age_months
<chr> <dbl> <dbl>
1 Ada 36 432
2 Linus 28 336
3 Grace 45 540
Differences from a plain data frame:
- Better printing — shows the dimensions and each column's type
(
<chr>text,<dbl>number,<int>integer,<lgl>logical,<fct>factor,<date>date), and only prints the first 10 rows of large tables, so your console isn't flooded. - Columns can refer to earlier columns while creating the tibble,
as
age_monthsdoes. - Stricter behaviour — no partial matching of column names, and
df[, "col"]always returns a tibble, never silently a vector.
Converting
library(tibble)
df <- data.frame(x = 1:2, y = c("a", "b"))
as_tibble(df)
# A tibble: 2 × 2
x y
<int> <chr>
1 1 a
2 2 b
as.data.frame() converts back if a function needs a plain data frame.
Row-by-row construction
tribble() lays data out in rows, which is handy for small lookup
tables:
library(tibble)
tribble(
~code, ~country,
"NG", "Nigeria",
"PE", "Peru"
)
# A tibble: 2 × 2
code country
<chr> <chr>
1 NG Nigeria
2 PE Peru
glimpse(df) (from dplyr or tibble) shows a transposed overview — every
column with its type and first values — ideal for wide datasets.