Convert tibble to list of matrices?

Suppose I have the following tibble:

library(dplyr)
N <- 100
I <- 5
K <- 10
X <- tidyr::expand_grid(N = 1:N,
                        I = 1:5,
                        K = 1:K) %>% 
  mutate(x = rnorm(n = N*I*K, mean = 5, sd = 2))

Created on 2021-01-11 by the reprex package (v0.3.0)

I would like to convert that tibble into a list of I NxK matrices.

I was able to create a list of tibbles as follows, but I would like to convert that into a list of matrices:

X2 <- X %>% 
  tidyr::pivot_wider(names_from = K, values_from = x) %>% 
  select(-N) %>% 
  group_by(I) %>% 
  tidyr::nest() %>% 
  pull(data)

Thanks!

Does this give you what you want?

X2 <- X %>% 
  tidyr::pivot_wider(names_from = K, values_from = x) %>% 
  select(-N) %>% 
  group_by(I) %>% 
  tidyr::nest() %>% 
  pull(data) %>% 
  purrr::map(as.matrix)
1 Like

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.