Forklift17
Forklift17

Reputation: 2477

How to get a list (or vector) of tibbles

In Python, I could do something like this:

import pandas as pd

s1 = pd.Series([1,2,3])
s2 = pd.Series([4,5,6])
combo = [s1, s2]

I want to do something similar in R. I tried this:

library(dplyr)

tbl1 <- tibble(1:3)
tbl2 <- tibble(4:6)
combo <- c(tbl1, tbl2)

But that destroys the dplyr data structure and just creates a list of lists.

How do I get a list (or vector) of tibbles?

Upvotes: 1

Views: 126

Answers (2)

jimbrig
jimbrig

Reputation: 127

As @akrun said you are looking for the list object, not an atomic vector (constructed via c()). You can further name the list objects, access them, and merge them as so:

# create datalist
datalist <- list(
   "tbl1" = tibble::tibble(a = 1:3, b = letters[1:3]),
   "tbl2" = tibble::tibble(a = 4:6, b = letters[4:6])
 )

# access tbl from list
datalist[["tbl1"]]

# merge into single data.frame/tibble
combined <- dplyr::bind_rows(datalist, .id = "table_name")

Upvotes: 2

akrun
akrun

Reputation: 887173

A data.frame/tibble/data.table are all list with added class attributes. When we do the concatenation, it removes those class attributes and results in a simple list of vector i.e. columns. If we want to preserve the class, wrap with list

combo <- list(tbl1, tbl2)

or as a named list

combo <- dplyr::lst(tbl1, tbl2)

Upvotes: 1

Related Questions