转换数据帧 R 列中的列表
convert a list in a colum of a data frame R
我想用列表中的列创建一个 data.frame 或 tibble,我试过这个
tlist <- list(A=matrix(runif(100),10), b=runif(10),bb=runif(20))
tibble(c=10,tlist)
但结果是
# A tibble: 3 x 2
c tlist
<dbl> <named list>
1 10 <dbl[,10] [10 × 10]>
2 10 <dbl [10]>
3 10 <dbl [20]>
我想要的是一行两列 c
和 tlist
# A tibble: 1 x 2
c tlist
<dbl> <named list>
1 10 <dbl[,10] [10 × 10] ... >
你需要再添加一层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]>
您必须进一步包装列表。
对于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
对于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)
对于data.table
library(data.table)
# Wrapping list inside list is enough
dt <- data.table(c=10, list_col=list(tlist=tlist))
我想用列表中的列创建一个 data.frame 或 tibble,我试过这个
tlist <- list(A=matrix(runif(100),10), b=runif(10),bb=runif(20))
tibble(c=10,tlist)
但结果是
# A tibble: 3 x 2
c tlist
<dbl> <named list>
1 10 <dbl[,10] [10 × 10]>
2 10 <dbl [10]>
3 10 <dbl [20]>
我想要的是一行两列 c
和 tlist
# A tibble: 1 x 2
c tlist
<dbl> <named list>
1 10 <dbl[,10] [10 × 10] ... >
你需要再添加一层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]>
您必须进一步包装列表。
对于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
对于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)
对于data.table
library(data.table)
# Wrapping list inside list is enough
dt <- data.table(c=10, list_col=list(tlist=tlist))