how to return n objects in purrr?

Consider this simple example

myfunc <- function(x){
  paste(x,c('a','b','c'))
}

tibble(var = c(1,2,3)) %>% 
  mutate(multi_output = map(var, ~myfunc(.x)))

# A tibble: 3 x 2
    var multi_output
  <dbl> <list>      
1     1 <chr [3]>   
2     2 <chr [3]>   
3     3 <chr [3]>

The problem is that I would like the multi_output to correspond to three different new columns, something like

  # A tibble: 3 x 4
    var v1    v2    v3   
  <dbl> <chr> <chr> <chr>
1     1 1 a   1 b   1 c  
2     2 2 a   2 b   2 c  
3     3 3 a   3 b   3 c

How can I achieve that?
Thanks!

Does this count as a solution?

library(purrr)
library(tibble)
library(tidyr)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
myfunc <- function(x){
  as.data.frame(t(paste(x,c('a','b','c'))))
}

tibble(var = c(1,2,3)) %>% 
  mutate(multi_output = map(var, ~myfunc(.x))) %>% 
  unnest(multi_output)
#> # A tibble: 3 x 4
#>     var V1    V2    V3   
#>   <dbl> <fct> <fct> <fct>
#> 1     1 1 a   1 b   1 c  
#> 2     2 2 a   2 b   2 c  
#> 3     3 3 a   3 b   3 c

Created on 2020-04-15 by the reprex package (v0.3.0)

1 Like

great! but what happens if the number of items in the lists is not the same across rows?

Here is a silly example of that.

library(purrr)
library(tibble)
library(tidyr)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
myfunc <- function(x){
  as.data.frame(t(paste(x,rep(x,x))))
}

tibble(var = c(1,2,3)) %>% 
  mutate(multi_output = map(var, ~myfunc(.x))) %>% 
  unnest(multi_output)
#> # A tibble: 3 x 4
#>     var V1    V2    V3   
#>   <dbl> <fct> <fct> <fct>
#> 1     1 1 1   <NA>  <NA> 
#> 2     2 2 2   2 2   <NA> 
#> 3     3 3 3   3 3   3 3

Created on 2020-04-15 by the reprex package (v0.3.0)

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