# 第 8 章 函数应用

## 8.1 灵活的语法

mysquare <- function(x) {
y <- x^2
return(y)
}

R语言里面，完成一件事情往往有很多种方法，比如

mysquare <- function(x) {
return(x^2)
}

mysquare <- function(x) { return(x^2) }

mysquare <- function(x) return(x^2)

mysquare <- function(x) {
x^2
}

mysquare <- function(x) x^2

## 8.2 多个参数

sum_two <- function(num1, num2) {
sum  <- num1 + num2
return(sum)
}

sum_two(num1 = 1, num2 = 2)
## [1] 3
sum_two(12, 9)
## [1] 21

norm_by_y <- function(num1, num2) {
result  <- (num1 - num2)/num2
return(result)
}

## 8.3 条件语句

if(condition) {
Do something
} else {
Alternative something
}

square_if <- function(num) {
if (is.numeric(num)) {
num^2
} else {
}
}

square_if("a")
## [1] "Your input is not numeric."
square_if(3)
## [1] 9

sum_two("a", "b")

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

x <- 0
check_number(x)
## [1] "Zero"

## 8.4 返回多个结果

mystat <- function(x){
meanval <- mean(x)
sdval <- sd(x)

list(sd = sdval, mean = meanval)
}

mystat <- function(x){
meanval <- mean(x)
sdval <- sd(x)

sd = sdval,
mean = meanval
)
}

## 8.5 更多

enlarge_icecream <- function(multi = 10) {
function(icecream) {
icecream * multi
}
}

x <- c(2, 3, 4.5)
x
## [1] 2.0 3.0 4.5

enlarge_icecream(multi = 100)(x)
## [1] 200 300 450