zachvac
zachvac

Reputation: 730

List Columns - Creating a data frame of data frames

I'd like to create a pretty simple data frame of data frames. I'd like the master data frame to have 100 rows, with two columns. One column is called "row" and has the numbers 1-100 and two other column called "df1" and "df2" that are each a data frame with one column "row" and the numbers 1-100. I've tried the following:

mydf <- data.frame(row=1:100)
for(i in 1:100){
  mydf$df1[i] <- data.frame(row=1:100)
  mydf$df2[i] <- data.frame(row=1:100)
}

But that creates lists not data frames and the columns are unnamed. I also tried:

mydf <- data.frame(row=1:100)
mydf <- mydf %>% mutate(df1=data.frame(row=1:100),df2=data.frame(row=1:100))

But that throws an error. It seems like what I'm doing shouldn't be too difficult, what am I doing wrong and how can I accomplish this?

Thanks.

Upvotes: 0

Views: 64

Answers (3)

Harlan Nelson
Harlan Nelson

Reputation: 1502

I think you should used nested data frames as described in https://www.rdocumentation.org/packages/tidyr/versions/0.6.1/topics/nest But for what you ask, you need the operator I.

mydf <- data.frame(row=1:100)
for(i in 1:100){
  mydf$df1[i] <- I(data.frame(row=1:100))
  mydf$df2[i] <- I(data.frame(row=1:100))
}
show(mydf)
mydf$df1

Upvotes: 0

Artem Sokolov
Artem Sokolov

Reputation: 13731

Use do on a per-row basis instead of mutate:

mydf <- data.frame( row = 1:100 ) %>% group_by(row) %>%
  do( df1 = data.frame(row=1:100), df2 = data.frame(row=1:100) ) %>% ungroup
# # A tibble: 100 x 3
#     row                    df1                    df2
#   <int>                 <list>                 <list>
# 1     1 <data.frame [100 x 1]> <data.frame [100 x 1]>
# 2     2 <data.frame [100 x 1]> <data.frame [100 x 1]>
# 3     3 <data.frame [100 x 1]> <data.frame [100 x 1]>
# ...

Upvotes: 2

Sotos
Sotos

Reputation: 51622

You can use replicate to achieve that, i.e.

mydf$df1 <- replicate(100, mydf)
mydf$df2 <- replicate(nrow(mydf), mydf) #I used nrow here to make it more generic

Upvotes: 2

Related Questions