반응형
(7) 함수
함수는 특정한 태스크를 하기 위한 구문들의 집합이다. R에는 in-built 함수들이 많이 있고 또한 직접 함수를 정의하여 사용할 수도 있다. 한 가지 주의할 점은 R에서 함수는 객체이다.
함수 정의
R에서 함수는 function() 키워드를 통해 만들 수 있다.
function_name <- function(arg_1, arg_2, ...) { Function body }
함수의 구성요소
- Function Name : 함수의 실제 이름이다. R environment에 해당 이름의 객체로 저장된다.
- Arguments : Arguments는 placeholder이다. 함수가 호출 될 때, arguments에 값이 할당된다. arguments는 없어도 되며, 또한 default 값을 가질 수 있다.
- Function Body : function이 하는 일을 기술한 구문들이다.
- Return Value : function body가 최종적으로 리턴한 값이다.
Built-in 함수
in-built 함수의 간단한 예에는 seq(), mean(), max(), sum() 등이 있다.
더 많은 in-built function 보기
https://cran.r-project.org/doc/contrib/Short-refcard.pdf
# Create a sequence of numbers from 32 to 44. print(seq(32,44)) # Find mean of numbers from 25 to 82. print(mean(25:82)) # Find sum of numbers frm 41 to 68. print(sum(41:68))
사용자 정의 함수
사용자 정의 함수의 예이다.
# Create a function to print squares of numbers in sequence. new.function <- function(a) { for(i in 1:a) { b <- i^2 print(b) } }
# Call the function new.function supplying 6 as an argument. new.function(6)
다음과 같이 argument의 이름을 명시적으로 지정하여 호출할 수도 있다.
# Create a function with arguments. new.function <- function(a,b,c) { result <- a * b + c print(result) } # Call the function by position of arguments. new.function(5,3,11) # Call the function by names of the arguments. new.function(a = 11, b = 5, c = 3)
Default 값
다음과 같이 함수 내부에 default 값을 선언할 수도 있다. argument가 아무것도 주어지지 않는다면 default 값을 사용한다.
# Create a function with arguments. new.function <- function(a = 3, b = 6) { result <- a * b print(result) } # Call the function without giving any argument. new.function() # Call the function with giving new values of the argument. new.function(9,5)
아래 튜토리얼을 참고한 포스팅입니다.
반응형
'Tools > R' 카테고리의 다른 글
R - (8) 문자열 (Strings) (0) | 2017.02.23 |
---|---|
R을 통한 2017년 대선 주자들 페이스북 분석 (5) | 2017.02.21 |
R - (6) 반복문 (0) | 2017.02.17 |
R - (5) If, else if, switch (0) | 2017.02.15 |
R - (4) 연산자 (0) | 2017.02.15 |