Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a data.frame where a column is a list

Tags:

list

dataframe

r

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 

This works, but not:

> 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 

Why?

Also, is there a way to create df (above) in a single call to data.frame?

like image 409
flodel Avatar asked Mar 03 '12 16:03

flodel


People also ask

Can a column in a DataFrame be a list?

You can get or convert the pandas DataFrame column to list using Series. values. tolist() , since each column in DataFrame is represented as a Series internally, you can use this function after getting a column you wanted to convert as a Series. You can get a column as a Series by using df.

How do I make a column into a DataFrame list?

Use the tolist() Method to Convert a Dataframe Column to a List. A column in the Pandas dataframe is a Pandas Series . So if we need to convert a column to a list, we can use the tolist() method in the Series . tolist() converts the Series of pandas data-frame to a list.

Can you include an R list as a column of a data frame?

Data frame columns can contain lists You can also create a data frame having a list as a column using the data. frame function, but with a little tweak. The list column has to be wrapped inside the function I.


1 Answers

Slightly obscurely, from ?data.frame:

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

(emphasis added).

So

data.frame(a=1:3,b=I(list(1,1:2,1:3))) 

seems to work.

like image 196
Ben Bolker Avatar answered Sep 20 '22 04:09

Ben Bolker