[英]Given a list of nested tibbles how do I map function to each object?
我有一個嵌套小標題列表(包括列表本身等,有點像 inception)。
library(tidyverse)
# example function I want to apply
fun1 <- function(data) {
minimum <- min(data$Sepal.Length)
return(minimum)
}
# example of nested list
list_nested_tibbles <- list(
list1 = iris %>% group_by(Species) %>% nest(),
list2 = iris %>% group_by(Species) %>% nest()
)
# applying function to one of the nested tibbles within the list
list_nested_tibbles$list1 %>% mutate(minimum = map_dbl(.x = data, ~ fun1(.x)))
#> # A tibble: 3 x 3
#> # Groups: Species [3]
#> Species data minimum
#> <fct> <list> <dbl>
#> 1 setosa <tibble [50 x 4]> 4.3
#> 2 versicolor <tibble [50 x 4]> 4.9
#> 3 virginica <tibble [50 x 4]> 4.9
# function fails if I apply across whole list
list_nested_tibbles %>% mutate(minimum = map_dbl(.x = data, ~ fun1(.x)))
#> Error in UseMethod("mutate"): no applicable method for 'mutate' applied to an object of class "list"
但是,我想同時將 function 應用於兩個列表項,我猜我需要某種嵌套的 map 語句?
任何幫助表示贊賞。
干杯。
以下是使用purrr
函數的方法:
map(list_nested_tibbles, ~ .x %>% mutate(minimum = map_dbl(data, ~ fun1(.x))))
$list1
# A tibble: 3 × 3
# Groups: Species [3]
Species data minimum
<fct> <list> <dbl>
1 setosa <tibble [50 × 4]> 4.3
2 versicolor <tibble [50 × 4]> 4.9
3 virginica <tibble [50 × 4]> 4.9
$list2
# A tibble: 3 × 3
# Groups: Species [3]
Species data minimum
<fct> <list> <dbl>
1 setosa <tibble [50 × 4]> 4.3
2 versicolor <tibble [50 × 4]> 4.9
3 virginica <tibble [50 × 4]> 4.9
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.