매퍼 소개

purrr로 배우는 중급 함수형 프로그래밍

Colin Fay

Data Scientist & R Hacker at ThinkR

purrr의 .f

함수:

  • .x의 각 요소에 대해
  • .f(.x, ...) 실행

숫자 $n$:

  • .x의 각 요소에 대해
  • .x[$n$] 실행

문자 벡터 $z$

  • .x의 각 요소에 대해
  • .x[$z$] 실행
purrr로 배우는 중급 함수형 프로그래밍

함수로서의 .f

함수일 때 .f는 다음 중 하나입니다:

  • 일반 함수
my_fun <- function(x) {
  round(mean(x))
}
map_dbl(visit_2014, my_fun)
 [1]  5526  6546  6097  7760
 [5]  7025  7162 10484  8256
 [9]  6558  7686  5723  5053

 

  • 람다(익명) 함수
map_dbl(visit_2014, function(x) {
  round(mean(x))
})
 [1]  5526  6546  6097  7760
 [5]  7025  7162 10484  8256
 [9]  6558  7686  5723  5053
purrr로 배우는 중급 함수형 프로그래밍

매퍼: 1부

매퍼: 단방향 수식을 사용한 익명 함수

# With one parameter 
map_dbl(visits2017, ~ round(mean(.x)))

# Is equivalent to 
map_dbl(visits2017, ~ round(mean(.)))

# Is equivalent to 
map_dbl(visits2017, ~ round(mean(..1)))
purrr로 배우는 중급 함수형 프로그래밍

매퍼: 2부

매퍼: 단방향 수식을 사용한 익명 함수

# With two parameters
map2(visits2016, visits2017, ~ .x + .y)

# Is equivalent to 
map2(visits2016, visits2017, ~ ..1 + ..2)
# With more than two parameters
pmap(list, ~ ..1 + ..2 + ..3)
purrr로 배우는 중급 함수형 프로그래밍

as_mapper()

as_mapper(): 람다 함수로 매퍼 객체 생성

# Classical function 
round_mean <- function(x){
    round(mean(x))
}
# As a mapper
round_mean <- as_mapper(~ round(mean(.x))))
purrr로 배우는 중급 함수형 프로그래밍

매퍼를 사용하는 이유

매퍼의 특징:

  • 간결함

  • 가독성

  • 재사용 가능

매퍼 생성

purrr로 배우는 중급 함수형 프로그래밍

연습해 봅시다!

purrr로 배우는 중급 함수형 프로그래밍

Preparing Video For Download...