Help creating a tibble that has a column made of tibbles?

I want to create a tibble that has a column that is made of tibbles.

In particular, I want to do what the code below does but from i in 1:n_rows. What is the best way of doing that?

library(dplyr)
library(tidyr)
n_rows <- 4000
n_cols <- 1000

# my data looks something like this
A <- matrix(data = rnorm(n=n_rows*n_cols), nrow = n_rows)
betas <- rnorm(n = n_rows)
# I want the first row of my tibble to look like this

i <- 1

my_data <- tibble(i=i,
                  beta = betas[i],
                  data = tibble(a = A[i,],
                                b = sample(c(1,2), size = n_cols, replace = T))) %>% 
  group_by(i, beta) %>% 
  nest()
my_data
#> # A tibble: 1 x 3
#>       i  beta data                
#>   <dbl> <dbl> <list>              
#> 1     1 -2.26 <tibble [1,000 × 1]>

What is the tidy way of doing this?

Created on 2019-05-24 by the reprex package (v0.2.1)

you re already doing it right, little fella. what do you want to do exactly?

My code only generates the the first row of the tibble. How would you do a tibble that has rows for in 1:4K ?

is this what you want young padawan?


tibble(idx = seq(1, n_rows)) %>%
  mutate(mytib = map(idx , ~tibble(i=.x,
                beta = betas[.x],
                data = tibble(a = A[.x,],
                              b = sample(c(1,2), size = n_cols, 
                                         replace = T)))))

# A tibble: 4,000 x 2
     idx mytib               
   <int> <list>              
 1     1 <tibble [1,000 x 3]>
 2     2 <tibble [1,000 x 3]>
 3     3 <tibble [1,000 x 3]>

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.