1

This is such a basic question, but I am stuck: The code is taken from here: https://www.geeksforgeeks.org/list-of-dataframes-in-r/

I have this list of dataframes of length 2.

# Create dataframe
df1 = data.frame(
  y1 = c(1, 2, 3),
  y2 = c(4, 5, 6)
)

# Create another dataframe
df2 = data.frame(
  y1 = c(7, 8, 9),
  y2 = c(1, 4, 6)
)

# Create list of data frame using list()
listOfDataframe = list(df1, df2)

Now I want that this list becomes a column in a data.frame. As my list is of length 2, I thought the dataframe should have two rows as I want each dataframe to be essentially on one row. So I try the following:

df_list_col = data.frame(a = 1:2, listOfDataframe)

But I get the following error:

Error in data.frame(a = 1:2, listOfDataframe) : 
  arguments imply differing number of rows: 2, 3

What am I missing here?

Lenn
  • 1,283
  • 7
  • 20
  • 1
    Wrap the list in `I`: `d = data.frame(I(listOfDataframe))`; `str(d)` – Henrik Jul 09 '21 at 11:18
  • Thanks a lot!! This also works, I just do not understand why this is necessary – Lenn Jul 09 '21 at 11:22
  • 1
    If you just do the ```data.frame(listOfDataframe)```then you see that the data.frame has 3 rows and 4 columns, what you try to do is adding "a" with 2 rows to that. The list length is not important here, but the number of rows of the data.frames in your list. – wiebke Jul 09 '21 at 11:34

1 Answers1

1

Break it down in two steps -

df <- data.frame(a = seq_along(listOfDataframe))
df$b <- listOfDataframe

df
#  a                b
#1 1 1, 2, 3, 4, 5, 6
#2 2 7, 8, 9, 1, 4, 6

df$b
#[[1]]
#  y1 y2
#1  1  4
#2  2  5
#3  3  6

#[[2]]
#  y1 y2
#1  7  1
#2  8  4
#3  9  6

Using tibble works directly -

tibble::tibble(a = seq_along(listOfDataframe), b = listOfDataframe)

# A tibble: 2 x 2
#     a b           
#  <int> <list>      
#1     1 <df [3 × 2]>
#2     2 <df [3 × 2]>
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213