Skip to content

tibble & readr

A tibble is a data frame that prints a preview, never matches a column name partially, and keeps its type when you subset it. readr reads delimited text into tibbles and writes them back out. Every example below that reads a file writes that file first, to a temporary path, so the page runs from top to bottom in a fresh R session.

Function Purpose
tibble() Build a tibble by column
tribble() Build a tibble by row
as_tibble(x, rownames = "id") Matrix or data frame to tibble, keeping row names
column_to_rownames() Move an ID column back to row names
enframe(), deframe() Named vector to tibble and back
read_csv(), read_tsv() Read comma or tab separated files
read_delim(delim = "|") Read any single character delimiter
spec() Print the guessed column types as code
problems() List values that failed to parse
read_lines() Read raw lines
readxl::read_excel() Read an Excel sheet or cell range
write_csv(), write_tsv() Write delimited files, compressed by extension
glimpse() One line per column
library(tibble)
library(readr)
library(dplyr)
# Match the printed width on this page.
options(width = 80)

A column can use a column defined above it in the same call, which data.frame() does not allow.

de_genes <- tibble(
gene = c("TP53", "BRCA1", "EGFR", "MYC", "KRAS"),
log2fc = c(2.3, -1.5, 0.8, 3.1, -0.4),
pvalue = c(0.001, 0.023, 0.15, 0.0003, 0.45),
significant = pvalue < 0.05
)
de_genes
# A tibble: 5 × 4
gene log2fc pvalue significant
<chr> <dbl> <dbl> <lgl>
1 TP53 2.3 0.001 TRUE
2 BRCA1 -1.5 0.023 TRUE
3 EGFR 0.8 0.15 FALSE
4 MYC 3.1 0.0003 TRUE
5 KRAS -0.4 0.45 FALSE

tribble() reads like the sample sheet it describes. Use it for small lookup tables.

sample_sheet <- tribble(
~sample_id, ~condition, ~replicate,
"S1", "control", 1L,
"S2", "control", 2L,
"S3", "treated", 1L,
"S4", "treated", 2L
)
sample_sheet
# A tibble: 4 × 3
sample_id condition replicate
<chr> <chr> <int>
1 S1 control 1
2 S2 control 2
3 S3 treated 1
4 S4 treated 2

A tibble has no row names, so a count matrix loses its gene IDs unless you move them into a column. The airway counts below are a real Bioconductor matrix with Ensembl IDs as row names.

The count subset credits Himes and colleagues, 2014, and Michael Love’s airway 1.32.0 package. The ExperimentData package distributes the count object under LGPL. This example selects four genes and four samples, then changes their table layout. The source and license notice identifies the original experiment and count object.

data("airway", package = "airway")
counts <- SummarizedExperiment::assay(airway, "counts")[1:4, 1:4]
count_tbl <- as_tibble(counts, rownames = "gene_id")
count_tbl
# A tibble: 4 × 5
gene_id SRR1039508 SRR1039509 SRR1039512 SRR1039513
<chr> <int> <int> <int> <int>
1 ENSG00000000003 679 448 873 408
2 ENSG00000000005 0 0 0 0
3 ENSG00000000419 467 515 621 365
4 ENSG00000000457 260 211 263 164

Back to a matrix with column_to_rownames()

Section titled “Back to a matrix with column_to_rownames()”

DESeq2 and limma want a numeric matrix with gene IDs as row names, so this is the trip back.

count_tbl |>
column_to_rownames("gene_id") |>
as.matrix()
SRR1039508 SRR1039509 SRR1039512 SRR1039513
ENSG00000000003 679 448 873 408
ENSG00000000005 0 0 0 0
ENSG00000000419 467 515 621 365
ENSG00000000457 260 211 263 164

Named vectors with enframe() and deframe()

Section titled “Named vectors with enframe() and deframe()”

enframe() turns a named vector into two columns. deframe() turns the first two columns back into a named vector, which is the shape a ranked list for GSEA takes.

fc_named <- c(TP53 = 2.3, BRCA1 = -1.5, EGFR = 0.8, MYC = 3.1)
fc_tbl <- enframe(fc_named, name = "gene", value = "log2fc")
fc_tbl
deframe(fc_tbl)
# A tibble: 4 × 2
gene log2fc
<chr> <dbl>
1 TP53 2.3
2 BRCA1 -1.5
3 EGFR 0.8
4 MYC 3.1
TP53 BRCA1 EGFR MYC
2.3 -1.5 0.8 3.1

A data frame matches $gene to gene_symbol without a word. A tibble returns NULL and raises a warning, caught here so the message prints.

df <- data.frame(gene_symbol = c("TP53", "BRCA1"))
tbl <- as_tibble(df)
df$gene
tryCatch(tbl$gene, warning = \(w) conditionMessage(w))
[1] "TP53" "BRCA1"
[1] "Unknown or uninitialised column: `gene`."

Single bracket subsetting of one column returns a vector from a data frame and a one column tibble from a tibble. Use pull() or [[ when the next function expects a vector.

df[, "gene_symbol"]
tbl[, "gene_symbol"]
[1] "TP53" "BRCA1"
# A tibble: 2 × 1
gene_symbol
<chr>
1 TP53
2 BRCA1

The results table below has the column names DESeq2 uses and one NA in padj, the value DESeq2 reports for a gene removed by independent filtering.

results <- tribble(
~gene_id, ~symbol, ~baseMean, ~log2FoldChange, ~pvalue, ~padj,
"ENSG00000141510", "TP53", 1523.4, 2.31, 1.2e-08, 6.0e-08,
"ENSG00000012048", "BRCA1", 845.2, -1.48, 3.4e-04, 8.5e-04,
"ENSG00000146648", "EGFR", 2310.8, 0.82, 0.021, 0.0315,
"ENSG00000136997", "MYC", 4021.5, 3.05, 5.6e-12, 3.4e-11,
"ENSG00000133703", "KRAS", 12.3, -0.41, 0.61, NA,
"ENSG00000171862", "PTEN", 980.1, -2.12, 8.9e-06, 2.7e-05
)
results_path <- tempfile(fileext = ".csv")
write_csv(results, results_path)
read_lines(results_path, n_max = 3)
[1] "gene_id,symbol,baseMean,log2FoldChange,pvalue,padj"
[2] "ENSG00000141510,TP53,1523.4,2.31,1.2e-8,6e-8"
[3] "ENSG00000012048,BRCA1,845.2,-1.48,3.4e-4,8.5e-4"

write_csv() and write_tsv() never write row names, always write UTF-8, and write a missing value as NA. Pass na = "" when the next tool expects an empty field.

readr guesses each column type from a sample of up to 1,000 rows, set by guess_max. show_col_types = FALSE hides the column report that it prints otherwise.

results_in <- read_csv(results_path, show_col_types = FALSE)
results_in
# A tibble: 6 × 6
gene_id symbol baseMean log2FoldChange pvalue padj
<chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 ENSG00000141510 TP53 1523. 2.31 1.20e- 8 6 e- 8
2 ENSG00000012048 BRCA1 845. -1.48 3.4 e- 4 8.5 e- 4
3 ENSG00000146648 EGFR 2311. 0.82 2.1 e- 2 3.15e- 2
4 ENSG00000136997 MYC 4022. 3.05 5.6 e-12 3.4 e-11
5 ENSG00000133703 KRAS 12.3 -0.41 6.1 e- 1 NA
6 ENSG00000171862 PTEN 980. -2.12 8.90e- 6 2.70e- 5

spec() prints the column specification as code. Paste it into col_types to fix the types for the next run.

spec(results_in)
cols(
gene_id = col_character(),
symbol = col_character(),
baseMean = col_double(),
log2FoldChange = col_double(),
pvalue = col_double(),
padj = col_double()
)

A compact string sets one type per column, where c is character, d double, i integer, l logical, f factor, D date, and _ skips the column. col_select reads only the columns you name.

read_csv(results_path, col_types = "ccdddd", col_select = c(symbol, padj))
# A tibble: 6 × 2
symbol padj
<chr> <dbl>
1 TP53 6 e- 8
2 BRCA1 8.5 e- 4
3 EGFR 3.15e- 2
4 MYC 3.4 e-11
5 KRAS NA
6 PTEN 2.70e- 5

readr compresses on write and decompresses on read when the path ends in .gz, .bz2, .xz, or .zip. The counts went out as <int> and come back as <dbl>, because readr guesses double for whole numbers. Set col_types when the type matters.

counts_path <- tempfile(fileext = ".tsv.gz")
write_tsv(count_tbl, counts_path)
read_tsv(counts_path, show_col_types = FALSE)
# A tibble: 4 × 5
gene_id SRR1039508 SRR1039509 SRR1039512 SRR1039513
<chr> <dbl> <dbl> <dbl> <dbl>
1 ENSG00000000003 679 448 873 408
2 ENSG00000000005 0 0 0 0
3 ENSG00000000419 467 515 621 365
4 ENSG00000000457 260 211 263 164

featureCounts writes one # line above the header. comment = "#" drops it, and so does skip = 1.

fc_path <- tempfile(fileext = ".txt")
writeLines(c(
"# Program:featureCounts v2.0.6; Command:\"featureCounts\" \"-a\" ...",
"Geneid\tChr\tStart\tEnd\tStrand\tLength\tS1.bam\tS2.bam",
"ENSG00000141510\tchr17\t7661779\t7687538\t-\t2579\t812\t945",
"ENSG00000012048\tchr17\t43044295\t43125483\t-\t7088\t433\t388"
), fc_path)
read_tsv(fc_path, comment = "#", show_col_types = FALSE)
# A tibble: 2 × 8
Geneid Chr Start End Strand Length S1.bam S2.bam
<chr> <chr> <dbl> <dbl> <chr> <dbl> <dbl> <dbl>
1 ENSG00000141510 chr17 7661779 7687538 - 2579 812 945
2 ENSG00000012048 chr17 43044295 43125483 - 7088 433 388

VCF annotations and many variant tools write a missing value as .. Without na, the numeric column comes back as character.

annot_path <- tempfile(fileext = ".tsv")
writeLines(c(
"variant\tgene\tsift_score\tclinvar",
"chr17:7676154\tTP53\t0.03\tPathogenic",
"chr7:55191822\tEGFR\t.\t.",
"chr12:25245350\tKRAS\t0.00\tPathogenic"
), annot_path)
read_tsv(annot_path, show_col_types = FALSE) |> pull(sift_score)
read_tsv(annot_path, na = c("", "NA", "."), show_col_types = FALSE)
[1] "0.03" "." "0.00"
# A tibble: 3 × 4
variant gene sift_score clinvar
<chr> <chr> <dbl> <chr>
1 chr17:7676154 TP53 0.03 Pathogenic
2 chr7:55191822 EGFR NA <NA>
3 chr12:25245350 KRAS 0 Pathogenic

When a value does not fit the column type, readr writes NA, warns, and records the row. problems() lists each failure.

bad_path <- tempfile(fileext = ".csv")
writeLines(c("gene,count", "TP53,812", "MYC,n/a", "EGFR,1504"), bad_path)
bad_counts <- read_csv(bad_path, col_types = "ci")
problems(bad_counts) |> select(row, col, expected, actual)
bad_counts
# A tibble: 1 × 4
row col expected actual
<int> <int> <chr> <chr>
1 3 2 an integer n/a
# A tibble: 3 × 2
gene count
<chr> <int>
1 TP53 812
2 MYC NA
3 EGFR 1504

Give read_csv() a vector of paths and an id column to record where each row came from. The purrr cheatsheet shows the map() version for files that need their own cleanup.

batch_paths <- file.path(tempdir(), c("batch1.csv", "batch2.csv"))
write_csv(results[1:2, c("symbol", "log2FoldChange")], batch_paths[1])
write_csv(results[3:4, c("symbol", "log2FoldChange")], batch_paths[2])
read_csv(batch_paths, id = "file", show_col_types = FALSE) |>
mutate(file = basename(file))
# A tibble: 4 × 3
file symbol log2FoldChange
<chr> <chr> <dbl>
1 batch1.csv TP53 2.31
2 batch1.csv BRCA1 -1.48
3 batch2.csv EGFR 0.82
4 batch2.csv MYC 3.05

readr 2.2 warns when you pass the data itself as a string. Wrap literal text in I(), a change that trips code copied from older tutorials.

read_csv(I("gene,count\nTP53,812\nMYC,1504"), show_col_types = FALSE)
# A tibble: 2 × 2
gene count
<chr> <dbl>
1 TP53 812
2 MYC 1504

read_lines() returns one string per line. It suits FASTA headers and other formats that are not tables.

The FASTA examples credit the UniProt Consortium for P04637 and P38398, under CC BY 4.0. Each example retains only the first sequence line and shortens the original header.

fasta_path <- tempfile(fileext = ".fa")
writeLines(c(
">sp|P04637|P53_HUMAN Cellular tumor antigen p53",
"MEEPQSDPSVEPPLSQETFSDLWKLLPENNVLSPLPSQAMDDLMLSPDDIEQWFTEDPGP",
">sp|P38398|BRCA1_HUMAN Breast cancer type 1 susceptibility protein",
"MDLSALRVEEVQNVINAMQKILECPICLELIKEPVSTKCDHIFCKFCMLKLLNQKKGPSQ"
), fasta_path)
fasta_lines <- read_lines(fasta_path)
fasta_lines[startsWith(fasta_lines, ">")]
[1] ">sp|P04637|P53_HUMAN Cellular tumor antigen p53"
[2] ">sp|P38398|BRCA1_HUMAN Breast cancer type 1 susceptibility protein"

A collaborator’s sheet often has a title block above the table and notes below it. readxl ships a demo workbook in that shape, and range reads only the cells you name. On a sheet with a known number of junk rows, skip and n_max do the same job.

The workbook example credits Hadley Wickham, Jennifer Bryan and the readxl authors for the readxl demonstration fixture. The example selects five rows and three columns from deaths.xlsx. The complete MIT notice accompanies this source credit.

library(readxl)
deaths_path <- readxl_example("deaths.xlsx")
excel_sheets(deaths_path)
read_excel(deaths_path, range = "arts!A5:C10")
[1] "arts" "other"
# A tibble: 5 × 3
Name Profession Age
<chr> <chr> <dbl>
1 David Bowie musician 69
2 Carrie Fisher actor 60
3 Chuck Berry musician 90
4 Bill Paxton actor 61
5 Prince musician 57

glimpse() prints one line per column with its type and first values. It fits a wide table on the screen where printing the tibble would not.

glimpse(results_in)
Rows: 6
Columns: 6
$ gene_id <chr> "ENSG00000141510", "ENSG00000012048", "ENSG00000146648"…
$ symbol <chr> "TP53", "BRCA1", "EGFR", "MYC", "KRAS", "PTEN"
$ baseMean <dbl> 1523.4, 845.2, 2310.8, 4021.5, 12.3, 980.1
$ log2FoldChange <dbl> 2.31, -1.48, 0.82, 3.05, -0.41, -2.12
$ pvalue <dbl> 1.2e-08, 3.4e-04, 2.1e-02, 5.6e-12, 6.1e-01, 8.9e-06
$ padj <dbl> 6.00e-08, 8.50e-04, 3.15e-02, 3.40e-11, NA, 2.70e-05
  • Tidyverse Essentials introduces the pipe, the core dplyr verbs, and a write_tsv() and read_tsv() round trip.
  • Data Structures covers the vectors, matrices, and data frames that a tibble builds on.
  • Inspecting Files shows how to look at a file on the command line before you read it into R.
  • The dplyr cheatsheet picks up where this page stops, once the table is in memory.

The readr package by Wickham, Hester, and Bryan reads rectangular text data.

The tibble package by Müller and Wickham supplies the tibble data frame.