创建一个data.frame,其中一列是列表

我知道如何添加列表列:


> 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

为什么?


另外,有没有办法df在单个调用中创建(上方)data.frame?


慕码人8056858
浏览 996回答 3
3回答

泛舟湖上清波郎朗

来自?data.frame:如果将列表或数据帧或矩阵传递给“ data.frame”,则好像每个组件或列都作为单独的参数传递(“ class.model.matrix”类的矩阵以及受“ I”保护的矩阵除外) ')。所以data.frame(a=1:3,b=I(list(1,1:2,1:3)))似乎有效。

海绵宝宝撒

如果您正在使用data.tables,则可以避免致电I()library(data.table)# the following works as intendeddata.table(a=1:3,b=list(1,1:2,1:3))&nbsp; &nbsp;a&nbsp; &nbsp; &nbsp;b1: 1&nbsp; &nbsp; &nbsp;12: 2&nbsp; &nbsp;1,23: 3 1,2,3

慕田峪7331174

data_frameS(所谓的不同tibbles,tbl_df,tbl)原生支持使用列表的列的创建data_frame构造函数。使用它们,加载与他们如许多库之一tibble,dplyr或tidyverse。> data_frame(abc = letters[1:3], lst = list(1:3, 1:3, 1:3))# A tibble: 3 × 2&nbsp; &nbsp; abc&nbsp; &nbsp; &nbsp; &nbsp;lst&nbsp; <chr>&nbsp; &nbsp; <list>1&nbsp; &nbsp; &nbsp;a <int [3]>2&nbsp; &nbsp; &nbsp;b <int [3]>3&nbsp; &nbsp; &nbsp;c <int [3]>它们实际上是data.frames在幕后,但有些修改。它们几乎总是可以正常使用data.frames。我发现的唯一例外是,当人们进行不适当的类检查时,它们会引起问题:> #no problem> data.frame(x = 1:3, y = 1:3) %>% class[1] "data.frame"> data.frame(x = 1:3, y = 1:3) %>% class == "data.frame"[1] TRUE> #uh oh> data_frame(x = 1:3, y = 1:3) %>% class[1] "tbl_df"&nbsp; &nbsp; &nbsp;"tbl"&nbsp; &nbsp; &nbsp; &nbsp; "data.frame"> data_frame(x = 1:3, y = 1:3) %>% class == "data.frame"[1] FALSE FALSE&nbsp; TRUE> #dont use if with improper testing!> if(data_frame(x = 1:3, y = 1:3) %>% class == "data.frame") "something"Warning message:In if (data_frame(x = 1:3, y = 1:3) %>% class == "data.frame") "something" :&nbsp; the condition has length > 1 and only the first element will be used> #proper> data_frame(x = 1:3, y = 1:3) %>% inherits("data.frame")[1] TRUE
打开App,查看更多内容
随时随地看视频慕课网APP