创建一个列,列为列表的数据框 [英] Create a data.frame where a column is a list

查看:129
本文介绍了创建一个列,列为列表的数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很想知道为什么以下作品:

I was curious to know why the following works:

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 in a single call to data.frame?

推荐答案

?data.frame p>

Slightly obscurely, from ?data.frame:


如果将列表或数据框或矩阵传递给data.frame,则如果每个组件或列已被作为一个单独的参数
传递(除了model.matrix类的矩阵和由
'I'保护的矩阵)。

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)))

似乎有效。

这篇关于创建一个列,列为列表的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆