# R語言函數

## 函數定義

``````function_name <- function(arg_1, arg_2, ...) {
Function body
}``````

## 函數組件

• 函數名稱 - 這是函數的實際名稱。 它以R名稱作爲對象存儲在R環境中。
• 參數 - 參數是一個佔位符。調用函數時，將值傳遞給參數。參數是可選的; 也就是說，函數可能不包含參數。參數也可以有默認值。
• 函數體 - 函數體包含一組語句，用於定義函數的作用。
• 返回值 - 函數的返回值是要評估/計算的函數體中的最後一個表達式。

R具有許多內置函數，可以直接在程序中調用，而不必定義它們。我們還可以創建和使用自己創建的函數，稱爲用戶定義函數。

## 內置函數

``````# 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))``````

``````[1] 32 33 34 35 36 37 38 39 40 41 42 43 44
[1] 53.5
[1] 1526``````

## 用戶自定義函數

``````# Create a function to print squares of numbers in sequence.
new.function <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}``````

``````# 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(10)``````

``````[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
[1] 36
[1] 49
[1] 64
[1] 81
[1] 100``````

``````# Create a function without an argument.
new.function <- function() {
for(i in 10:20) {
print(i^2)
}
}

# Call the function without supplying an argument.
new.function()``````

``````[1] 100
[1] 121
[1] 144
[1] 169
[1] 196
[1] 225
[1] 256
[1] 289
[1] 324
[1] 361
[1] 400``````

``````# Create a function with arguments.
new.function <- function(a,b,c) {
result <- a * b + c
print(result)
}

# 按參數的順序來提供值調用
new.function(10,20,30)

# 按參數的名稱來提供值調用
new.function(a = 10, c = 30, b = 20)``````

``````[1] 230
[1] 230``````

``````# Create a function with arguments.
new.function <- function(a = 10, b = 20) {
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(11, 22)``````

``````[1] 200
[1] 242``````

## 懶惰計算函數

``````# Create a function with arguments.
new.function <- function(a, b) {
print(a^2)
print(a)
print(b)
}

# Evaluate the function without supplying one of the arguments.
new.function(8)``````

``````[1] 64
[1] 8
Error in print(b) : 缺少參數"b",也沒有缺省值``````