创建一个 data.frame,其中一列是一个列表
问题描述:
我知道如何添加列表列:
I know how to add a list column:
> df <- data.frame(a=1:3)
> df$b <- list(1:1, 1:2, 1:3)
> df
a b
1 1 1
2 2 1, 2
3 3 1, 2, 3
这行得通,但不行:
> df <- data.frame(a=1:3, b=list(1:1, 1:2, 1:3))
Error in data.frame(1L, 1:2, 1:3, check.names = FALSE, stringsAsFactors = TRUE) :
arguments imply differing number of rows: 1, 2, 3
为什么?
另外,有没有办法在一次调用 data.frame
中创建 df
(上面)?
Also, is there a way to create df
(above) in a single call to data.frame
?
答
有点晦涩,来自?data.frame
:
如果一个列表或数据框或矩阵被传递给‘data.frame’,它就像如果每个组件或列都作为单独的参数传递(除了model.matrix"类的矩阵和那些受保护的矩阵‘我’).
If a list or data frame or matrix is passed to ‘data.frame’ it is as if each component or column had been passed as a separate argument (except for matrices of class ‘"model.matrix"’ and those protected by ‘I’).
(强调).
所以
data.frame(a=1:3,b=I(list(1,1:2,1:3)))
似乎有效.