简体   繁体   English

当 function 返回列表时,使用 map 创建列

[英]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?如果我有一个 function 返回一个列表,我想通过输入map将其作为 data.frame 中的列返回,最好的方法是什么? 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. tidyr::unnest可用,但当您不控制迭代步骤时,它似乎更有用。

One alternative for unnest is to use unnest_wider to create the new columns. unnest的一种替代方法是使用unnest_wider创建新列。 But maybe you are still looking for something to do that in the map step?但也许您仍在寻找在map步骤中执行此操作的方法?

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感兴趣,如下所示:

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

Output: Output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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