处理未命名列表

使用 purrr 掌握函数式编程基础

Auriel Fournier

Instructor

先看管道

output <-  function_one() %>%
            function_two()

而不是需要

output1 <- function_one()

output <- function_two(output1)
使用 purrr 掌握函数式编程基础

我的列表有名称吗?

不使用管道

names(survey_data)
"LakeErieS" "LakeErieN" "LakeErieW" "LakeErieE"

使用管道

survey_data %>%
        names()
"LakeErieS" "LakeErieN" "LakeErieW" "LakeErieE"
使用 purrr 掌握函数式编程基础

没有名称?设定一个!

library(repurrrsive)
data(sw_films)
str(sw_films)
List of 14
 $ title        : chr "A New Hope"
 $ episode_id   : int 4
 $ opening_crawl: chr "It is a period of ..."
 $ director     : chr "George Lucas"
 ...
sw_films <- sw_films %>%
  set_names(map_chr(sw_films, "title"))
names(sw_films)
[1] "A New Hope"          "Attack of the Clones"   
[3] "The Phantom Menace"  "Revenge of the Sith"    
[5] "Return of the Jedi"  "The Empire Strikes Back"
[7] "The Force Awakens"
使用 purrr 掌握函数式编程基础

map() 内的管道

waterfowl_data

 

$LakeErieS
[1] 0 0 10 5

$LakeErieN
[1] 0 0 1000 5

$LakeErieW
[1] 10000 0 0 1

$LakeErieE
[1] 10 10 5 0
map(waterfowl_data, ~.x %>% 
                sum() %>% 
                log())
$LakeErieS
[1] 2.70805

$LakeErieN
[1] 6.912743

$LakeErieW
[1] 9.21044

$LakeErieE
[1] 3.218876
使用 purrr 掌握函数式编程基础

Let's purrr-actice!

使用 purrr 掌握函数式编程基础

Preparing Video For Download...