# 2 控制結構與函數

## 2.1 Conditionals

if ("condition is satisfied") {
"do something"
}

x <- 3
if (x > 0) {
print("Positive")
}
## [1] "Positive"

if ("condition is satisfied"){
"do something"
} else {
"otherwise do something else"
}

x <- 0
if (x > 0) {
print("Positive")
} else {
print("Negative")
}

x <- 0
if (x > 0) {
print("Positive")
} else if (x < 0) {
print("Negative")
} else {
print("Zero")
}

ifelse("condition", "task if TRUE", "task if FALSE")

x <- 9
ifelse(x > 0, "Positive", "Negative")
## [1] "Positive"

ifelse((1 : 10) < 5, "Fail", "Pass")
##  [1] "Fail" "Fail" "Fail" "Fail" "Pass" "Pass" "Pass" "Pass" "Pass" "Pass"

## 2.2 Loops

for 用於重複次數預先指定的時候，while 則反之，將持續運行直到條件無法滿足。

### 2.2.1for 迴圈

for 迴圈的語法為：

for ("counter" in "vector of indices") {
"do something"
}

for (i in 1 : 10) {
print(i)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9
## [1] 10

v <- c()

s <- 0
for (i in 1 : 10) {
s <- s + i
v[i] <- s
}
v
##  [1]  1  3  6 10 15 21 28 36 45 55

odd <- 2 * (1 : 10) - 1
for (i in odd) {
print(i)
}
## [1] 1
## [1] 3
## [1] 5
## [1] 7
## [1] 9
## [1] 11
## [1] 13
## [1] 15
## [1] 17
## [1] 19

for (i in 1 : 10) {
if (i < 5) {
print("Fail")
} else {
print("Pass")
}
}
## [1] "Fail"
## [1] "Fail"
## [1] "Fail"
## [1] "Fail"
## [1] "Pass"
## [1] "Pass"
## [1] "Pass"
## [1] "Pass"
## [1] "Pass"
## [1] "Pass"

### 2.2.2while 迴圈

while ("condition holds") {
"do something"
}

i <- 0
while (i < 10) {
print(c(i,"is less than 10"))
i <- i + 1
}
## [1] "0"               "is less than 10"
## [1] "1"               "is less than 10"
## [1] "2"               "is less than 10"
## [1] "3"               "is less than 10"
## [1] "4"               "is less than 10"
## [1] "5"               "is less than 10"
## [1] "6"               "is less than 10"
## [1] "7"               "is less than 10"
## [1] "8"               "is less than 10"
## [1] "9"               "is less than 10"

## 2.3 Functions and Operators

### 2.3.1 創建新函數

R 本身就有很多預設的函數，如 mean() 可以取平均，sum() 可以加總，sqrt() 可以計算數字的平方根，log()exp() 可以計算數字的對數值與指數值，sin()cos()tan() 可以計算三角函數值，is.logical() 可以確認型態是否是 logical。

function.name <- function(argument1, argument2,...) {
"body function"
}

f <- function(x, y) {
x ^ 2 - y / 5  # the output is the evaluation of last line
}

f <- function(x, y) x ^ 2 - y / 5

f <- function(x, y) {
return (x ^ 2 - y / 5)
}

### 2.3.2 引數的預設值

funtion.name <- function(name.argument1=default.value1,
name.argument2=default.value2,...) {
"body function"
}

mat.vec <- function(a, b=2, flag=FALSE){
if (flag) {
matrix(1 : a, nrow=b)
} else {
1:a
}
}

items <- function(x) list(len=length(x),total=sum(x), mean=mean(x))

data <- 1 : 10
result <- items(data)
result
## $len ## [1] 10 ## ##$total
## [1] 55
##
## $mean ## [1] 5.5 如果我們想查看函數是如何構成的，可以直接輸入其名，如： log ## function (x, base = exp(1)) .Primitive("log") 如果想要套用函數在多個元素時，可以使用 lapply(list, function)，其會把函數套用到 vector 或 list 的所有元素。sapply() 則類似於 lapply()，不同的是會把輸出簡化成向量或矩陣，而不是元素。其使用範例如： salutation <- function(x) print("Hello") # Note that this output does not depend on the value of x output <- sapply(1 : 5, salutation) ## [1] "Hello" ## [1] "Hello" ## [1] "Hello" ## [1] "Hello" ## [1] "Hello" 或者也可以簡化成： output <- sapply(1 : 5, function(x) print("Hello")) ## [1] "Hello" ## [1] "Hello" ## [1] "Hello" ## [1] "Hello" ## [1] "Hello" 以內建的 cars datasets 為例，其有兩個變數：speeddist。當我們想要計算這兩者的算術平均，可以： lapply(cars, mean) ##$speed
## [1] 15.4
##
## \$dist
## [1] 42.98

sapply(cars, mean)
## speed  dist
## 15.40 42.98

### 參考文獻

Zamora Saiz, Alfonso, Carlos Quesada González, Lluís Hurtado Gil, and Diego Mondéjar Ruiz. 2020. An Introduction to Data Analysis in R: Hands-on Coding, Data Mining, Visualization and Statistics from Scratch. Use R! Cham: Springer International Publishing. https://doi.org/10.1007/978-3-030-48997-7.