Reputation: 2072
I would like to create a data.frame or tibble with a column from a list, I tried this
tlist <- list(A=matrix(runif(100),10), b=runif(10),bb=runif(20))
tibble(c=10,tlist)
but the result is
# A tibble: 3 x 2
c tlist
<dbl> <named list>
1 10 <dbl[,10] [10 × 10]>
2 10 <dbl [10]>
3 10 <dbl [20]>
what I would like is a tibble with one row and two columns c
and tlist
# A tibble: 1 x 2
c tlist
<dbl> <named list>
1 10 <dbl[,10] [10 × 10] ... >
Upvotes: 0
Views: 60
Reputation: 96
You have to wrap the list further.
For tibble
:
# Wrap list inside list
tib <- tibble(c=10, list_col = list(tlist=tlist))
str(tib$list_col)
# list_col is a list with all the rows (now only tlist) in this column
str(tib$list_col$tlist)
str(tib$list_col[[1]])
# original tlist on first row
For data.frame
# List of list does not work for data.frame. Treat 'as is' with I()
df <- data.frame(c=10, list_col=I(list(tlist123=tlist)))
# Mind that this sets the row names to the names of the inner list (tlist123 here)
For data.table
library(data.table)
# Wrapping list inside list is enough
dt <- data.table(c=10, list_col=list(tlist=tlist))
Upvotes: 0
Reputation: 1452
You need add one more layer of list()
tlist <-list(list(A=matrix(runif(100),10), b=runif(10),bb=runif(20)))
tibble(c=10,tlist)
# A tibble: 1 x 2
c tlist
<dbl> <list>
1 10 <named list [3]>
Upvotes: 2