기본 인수

R 함수 작성 입문

Richie Cotton

Data Evangelist at DataCamp

toss_coin() 문제

toss_coin <- function(n_flips, p_head) {
  coin_sides <- c("head", "tail")
  weights <- c(p_head, 1 - p_head)
  sample(coin_sides, n_flips, replace = TRUE, prob = weights)
}

시그니처에서 기본값 설정

toss_coin <- function(n_flips, p_head = 0.5) {
  coin_sides <- c("head", "tail")
  weights <- c(p_head, 1 - p_head)
  sample(coin_sides, n_flips, replace = TRUE, prob = weights)
}
R 함수 작성 입문

기본값 템플릿

my_fun <- function(data_arg1, data_arg2, detail_arg1 = default1) {
  # Do something
}
R 함수 작성 입문

기타 기본값 유형

args(median)
function (x, na.rm = FALSE, ...)
library(jsonlite)
args(fromJSON)
function (txt, simplifyVector = TRUE, simplifyDataFrame = simplifyVector, 
    simplifyMatrix = simplifyVector, flatten = FALSE, ...)
R 함수 작성 입문

NULL 기본값

관례적으로, 이는 다음을 의미합니다.

이 인수는 함수가 특별히 처리합니다. 문서를 확인하세요.

args(set.seed)
function (seed, kind = NULL, normal.kind = NULL)
R 함수 작성 입문

범주형 기본값

  1. 시그니처에 문자 벡터를 전달합니다.
  2. 본문에서 match.arg()를 호출합니다.
args(prop.test)
function (x, n, p = NULL, alternative = c("two.sided", "less", "greater"), 
  conf.level = 0.95, correct = TRUE)

본문에서

alternative <- match.arg(alternative)
R 함수 작성 입문

분위수로 벡터 나누기

cut_by_quantile <- function(x, n, na.rm, labels, interval_type) {
  probs <- seq(0, 1, length.out = n + 1)
  quantiles <- quantile(x, probs, na.rm = na.rm, names = FALSE)
  right <- switch(interval_type, "(lo, hi]" = TRUE, "[lo, hi)" = FALSE)
  cut(x, quantiles, labels = labels, right = right, include.lowest = TRUE)
}
  • x: 구간으로 나눌 숫자 벡터
  • n: x를 나눌 구간 개수
  • na.rm: 결측값을 제거할지 여부
  • labels: 구간 레이블(문자)
  • interval_type: 구간을 왼쪽/오른쪽 중 어디를 열지
R 함수 작성 입문

고양이 심장 무게

고양이 심장 무게의 스트립 플롯. 범위는 3~20g.

quantile(cats$Hwt)
    0%    25%    50%    75%   100% 
 6.300  8.950 10.100 12.125 20.500
1 data(cats, package = "MASS")
R 함수 작성 입문

분위수로 나누기

이전 슬라이드의 스트립 플롯에 색을 입혔습니다. 왼쪽부터 빨강, 초록, 청록, 보라색 점.

cut(x, quantile(x))
R 함수 작성 입문

연습해 봅시다!

R 함수 작성 입문

Preparing Video For Download...