You are on page 1of 3

R 函數 (副檔名 .

R)
 函數視為一個變數,function 後的 () 不可省略
 函數內容用 {} 包含,只有一行指令 {} 可以不寫
 myfun <- function()
{
cat("This is an R function!\n")
}
 myfun:顯示 myfun 函數內容 myfun():執行 myfun 函數
 引數傳入
 myfun <- function(first, second)
cat(sprintf("We study %s and %s\n", first, second))
myfun1 <- function(first, second)
cat(first, "+", second, "=", first+second)
myfun2 <- function(first, second = "Network")
cat(sprintf("We study %s and %s\n", first, second))
myfun3 <- function(first, second = "Network", ...)
cat(sprintf("We study %s and %s\n", first, second))
 透過引數相對位置
 myfun("AI", "Big Data") myfun1(3, 5)
 透過引數名稱
 myfun(first = "R", second = "Python") myfun(second = "Python", first = "R")
 myfun(first = "IoT", "Cloud computing") myfun(second = "IoT", "Cloud computing")
 預設引數值
 myfun2("Software") myfun2("Software", "System")
 附加引數
 myfun1("AI", "Machine Learning", "IoT") myfun3("AI", "Machine Learning", "IoT")
 回傳值
 自動回傳最後一個指令計算出來的值 (不建議使用)
 使用 return 回傳值,可指定資料型式
 myfun <- function(x, y)
x+y; x*y
myfun1 <- function(x, y)
{
z <- x+y; w <- x*y
return(c(z, w))
}
 myfun(3, 5) myfun1(3, 5) n <- myfun1(3, 5)

 全域變數 vs. 區域變數


1
 函數中使用 <<- 可將變數傳回主程式
 全域變數請注意初始值的設定
 盡量不要使用全域變數

流程控制
 邏輯判斷式
 > >= < <= == != ! && & || |
 向量運算時,& 和 | 會檢測向量中每一個元素,&& 和 || 只會檢測第一個元素
 if-else
 myfun <- function(x)
{
if (x>=60)
cat("Pass!")
else if (x >= 50)
cat("Warning!")
else
cat("Fail!!")
}
 不能用 elseif
 {} 拿掉?
 ifelse(test, yes, no)
 x <- 6 y <- 3 z <- c(3, -2, 7, 10, 0) w <- c(3, NA, 7, 10, 0)
ifelse(x>5, "Yes", "No") ifelse(x>5, x*2, x^2) ifelse(x>5, x*2, "No")
# 將 x 換成 y、z、w 分別測試
 x <- c(1, 3, 2, 4) y <- c(4, 3, 2, 1)
ifelse(x<3 & y>1, "Yes", "No") ifelse(x<3 && y>1, "Yes", "No")
 switch (自行測試)

迴圈
 R 語言的迴圈執行效能不佳,盡量不要使用
 之後介紹的 plyr 和 dplyr packages 可達到迴圈的功能
 for 迴圈
 for (i in 1:10) # 用 numeric vector 當 index
cat(sprintf("%s: %2d\n", LETTERS[i], sum(1:i)))
 for (i in seq(1, 5, by = 0.5))
cat(i, "\n")

 fruit <- c("Apple", "Cherry", "Pear") # 用 character vector 當 index


fruitlength <- rep(NA, length(fruit))
2
names(fruitlength) <- fruit
print(fruitlength)
cat("-----\n")
for(i in fruit)
{
cat(i, " ")
fruitlength[i] <- nchar(i)
}
cat("\n-----\n")
print(fruitlength)
 while 迴圈
 x <- 1
while (x<=10)
{
cat(x, ":", sum(1:x), "\n")
x <- x+1
}
 next and break
 for (i in 1:10)
{
if (i==3 | i==7) next # 跳過該 iteration
cat("Iteration", i, "\n")
}
 for (i in 1:10)
{
if (i>5) break # 結束迴圈
cat("Iteration", i, "\n")
}
 repeat 迴圈
 x <- 1
repeat
{
if (x>10) break
cat(x, ":", sum(1:x), "\n")
x <- x+1
}

You might also like