Skip to content

Instantly share code, notes, and snippets.

@lovetoken
Created February 16, 2016 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lovetoken/2e362694a649a9513f67 to your computer and use it in GitHub Desktop.
Save lovetoken/2e362694a649a9513f67 to your computer and use it in GitHub Desktop.
Gist embeded

인자 기본값을 input data 에 따라 상호적으로 설정되는 함수 정의 방법에 대해 질문드립니다.


질문이 있습니다.
질문내용은 객체지향 프로그래밍과 조금이라도 관련된 질문이지 않을까 싶습니다.
(객체지향 프로그래밍 대단하면서도 참 어려운 것 같습니다. ㅜㅜ)

질문은 아래 예시로써 자세히 드리고자 합니다.
R에서 인자 기본값이 input 되는 데이터에 따라 상호적(interactive)으로 결정되는 함수 정의 방법이 궁금합니다.
예를들어

x <- 1:5
attr(x, "div") <- 2

1, 2, 3, 4, 5 벡터이며, 추가적으로 div 라는 명칭의 속성값 2가 들어있는 객체입니다.
또한 사용자 함수 myfun1()를 하나 아래와 같이 정의 하였는데요

myfun1 <- function(input){
	# 함수 실행 조건
	stopifnot(input %>% is.numeric)
	stopifnot(attributes(input)$div %>% is.numeric)
  
	# 함수 본문
	div <- attributes(input)$div
	return(sum(input)/div)
}

간단히 설명하면 벡터의 모든 값들을 더한 후 div 속성값으로 나눈 값을 반환시키는 함수입니다.
전제조건이 있는데 반드시 input 인자는 numeric 이어야 하고 div 라는 속성이 있어야 하며 이 속성값 역시 numeric 으로 가져야 실행됩니다.
방금만든 x 객체를 myfun1() 에 넣어 실행해본 결과입니다.

myfun1(x)
## [1] 7.5

자 이러한 상황에서 제가 원하는건 함수 안에 사용자가 나눠지는 값을 조절할 수 있는 인자를 하나 더만들고, 사용자가 조절을 할 수 있되 그 기본값은 inputdiv 속성값을 가져오고자 하는 것 입니다.
이를 만족하는 함수를 제 머리로 만들어 보자면

myfun2 <- function(input, div=attributes(input)$div){
	# 함수 실행 조건
	stopifnot(input %>% is.numeric)
	stopifnot(attributes(input)$div %>% is.numeric)
  
	# 함수 본문
	return(sum(input)/div)
}
myfun2(x)
## [1] 7.5

!!? 되는군요


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment