简体   繁体   中英

Create columns with map when a function returns a list

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.

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 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM