![](/img/trans.png)
[英]R - using map to apply a list function to dataframe column and create new columns with elements of the list
[英]Create columns with map when a function returns a list
如果我有一个 function 返回一个列表,我想通过输入map
将其作为 data.frame 中的列返回,最好的方法是什么? 例如:
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]>
我希望的是这样的:
#> # A tibble: 1 × 3
#> foo one two
#> <chr> <chr> <chr>
#> 1 bar ele1 ele2
tidyr::unnest
可用,但当您不控制迭代步骤时,它似乎更有用。
unnest
的一种替代方法是使用unnest_wider
创建新列。 但也许您仍在寻找在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
我喜欢安德鲁的方法,但你可能也对data.table
感兴趣,如下所示:
data.table(foo ="bar")[, c("one", "two"):= return_list(foo)][]
Output:
foo one two
<char> <char> <char>
1: bar ele1 ele2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.