Purrr spread output of map to new list columns instead of one column


#1

how do i manipulate with purrr verbs v0 to return a 2x4 tibble where columns 2:4 are the nested outputs of the v(), ie names(v1) is c('x','a','b','c') instead of a 2x2 c('x','out') (which is what i get now)

v0 <- as_tibble(data.frame(x=c(15,30)))
v <- function(x) list(a=mtcars[1:x,],b=iris[1:x,],c=volcano[1:x,])
v1 <- v0%>%mutate(out=purrr::map(x,v))

obviously the elements arent assumed to be just matrices and data.frames but any class that is consistent across rows


#2

here is one way. is there a more efficient one?

v <- function(x) list(a=mtcars[1:x,],b=iris[1:x,],c=volcano[1:x,])

v1 <- data.frame(x=c(15,30))%>%
do(cbind(x=.$x,as_tibble(transpose(purrr::map(.$x,v)))))

#3

Maybe:

f6 <- rlang::exprs(a = map(x, ~ mtcars[1:.x, ]), 
                   b = map(x, ~ iris[1:.x, ]), 
                   c = map(x, ~ volcano[1:.x, ]))
mutate(v0, !!! f6)

# # A tibble: 2 x 4
#       x a                      b                     c    
#   <dbl> <list>                 <list>                <lis>
# 1  15.0 <data.frame [15 × 11]> <data.frame [15 × 5]> <dbl…
# 2  30.0 <data.frame [30 × 11]> <data.frame [30 × 5]> <dbl…

Unsure about efficiency.


If you want to minimize modifications of existing code and risks of typos, maybe this instead where you just have to replace function(x) list(.... with rlang::exprs(....:

f8 <- rlang::exprs(a = mtcars[1:x, ], 
                   b = iris[1:x, ], 
                   c = volcano[1:x, ])
f9 <- map(f8, ~ rlang::expr(map(x, function(x) !! .x)))
mutate(v0, !!! f9)