Home > database >  Create columns with map when a function returns a list
Create columns with map when a function returns a list

Time:04-28

If I had a function that returned a list and I wanted to map over inputs to return that as columns in a data.frame what would be the best approach? For example:

library(purrr)
library(dplyr)

return_list <- function(arg) {
  if (arg == "bar") {
    return(
      list(
        one = "ele1",
        two = "ele2"
      )
    )
  }
}

tibble(foo = "bar") %>%
  mutate(col = map(foo, return_list))
#> # A tibble: 1 × 2
#>   foo   col             
#>   <chr> <list>          
#> 1 bar   <named list [2]>

What I am hoping for is something like this:

#> # A tibble: 1 × 3
#>   foo   one   two  
#>   <chr> <chr> <chr>
#> 1 bar   ele1  ele2

tidyr::unnest is available but that seems to more useful when you don't control the iteration step.

CodePudding user response:

One alternative for unnest is to use unnest_wider to create the new columns. But maybe you are still looking for something to do that in the map step?

library(tidyverse)

tibble(foo = "bar") %>%
  mutate(col = map(foo, return_list)) %>% 
  unnest_wider(col)

#  foo   one   two  
#  <chr> <chr> <chr>
#1 bar   ele1  ele2 

CodePudding user response:

I like Andrew's approach, but you may also be interested in data.table, as below:

data.table(foo ="bar")[, c("one", "two"):= return_list(foo)][]

Output:

      foo    one    two
   <char> <char> <char>
1:    bar   ele1   ele2
  • Related