羅
羅左欣 8 years ago
請參考 https://stat.ethz.ch/R-manual/R-devel/library/stats/html/sd.html
羅
羅左欣 8 years ago
請參考 https://stat.ethz.ch/R-manual/R-devel/library/stats/html/lm.html
羅
羅左欣 8 years ago
請參考 https://zh.wikipedia.org/wiki/%E6%83%B0%E6%80%A7%E6%B1%82%E5%80%BC
羅
羅左欣 8 years ago
Concatenate Strings : https://stat.ethz.ch/R-manual/R-devel/library/base/html/pa
- 20151019 [Coursera] R Programming (8)
- 整理自 R Programming (Week 2) -- Function
- [ Week 2 課程內容 ]
- [ 筆記內容 ]
- (一)Functions (part 1)
- [ 重點整理 ] 關於函數 - functions
- 1. 基本概念
- 2. 參數
- 3. 使用方式
- (二)Functions (part 2)
- [ 重點整理 ] 函數的定義與使用
- 1. 自訂函數
- 2. 惰性求值 - Lazy Evaluation
- 3. 特殊參數 - "..."
整理自 R Programming (Week 2) -- Function
Control Structures - Introduction[0:54](已完成)Control Structures - If-else[1:58](已完成)Control Structures - For loops[4:25](已完成)Control Structures - While loops[3:22](已完成)Control Structures - Repeat, Next, Break[4:57](已完成)Your First R Function[10:29](僅觀看)(一)Functions (part 1)
# function() 的使用
f <- function(arguments) { # arguments 參數 (在這裡是"形式"參數)
## Do something interesting
}
function(arguments) { # "形式參數"
...
}
# 計算標準差函數"sd()",其預設的用法為 "sd(x, na.rm = FALSE)"
# 用"sd()"讀入一個名為"x"的向量、用"na.rm"來判斷是否移除向量裡的缺失值。
> mydata <- rnorm(100) # 模擬100個正態分布的隨機數值,並將結果存入"mydata"
>
> sd(mydata) # 沒有對參數進行命名,所以預設"mydata"為第一個參數並將其傳遞給函數
[1] 0.9992897
>
> sd(x = mydata) # 對參數"x"進行命名,"x = mydata"
[1] 0.9992897
>
> sd(x = mydata, na.rm = FALSE) # 對所有參數進行命名,令"x = mydata, na.rm = FALSE"
[1] 0.9992897
>
> sd(na.rm = FALSE, x = mydata) # 對所有參數進行命名,令"x = mydata, na.rm = FALSE"
[1] 0.9992897
>
> sd(na.rm = FALSE, mydata) # 對調參數的順序,令"na.rm = FALSE, x = mydata"
[1] 0.9992897
> # 儘管可以對調參數的位置,但是不建議這樣做,因為很容易搞混。
# 使用"args()"來顯示"lm()"所有可使用的參數
> args(lm) # 顯示lm()所有可使用的參數
function (formula, data, subset, weights, na.action,
method = "qr", model = TRUE, x = FALSE,
y = FALSE, qr = TRUE, singular.ok = TRUE,
contrasts = NULL, offset, ...)
(二)Functions (part 2)
f <- function(a, b = 1, c = 2, d = NULL) {
}
> f <- function(a, b) { # 在函數主體只用了一個參數,求"a"的平方,並回傳結果。
+ a^2
+ }
>
> f(2)
[1] 4
> f <- function(a, b) {
+ print(a)
+ print(b)
+ }
>
> f(45)
[1] 45
Error in print(b) : argument "b" is missing, with no default
# 傳遞"..."之前的參數,在此為"(x, y, type = "1")"
> myplot <- function(x, y, type = "1", ...) {
+ plot(x, y, type = type, ...) # 傳遞"..."之前的參數,在此為"(x, y, type = type)"
+ }
> mean
function (x, ...)
UseMethod("mean")
<bytecode: 0x0848c528>
<environment: namespace:base>
>
# paste() : 將一組字串連接起來,來新建一個新的字串或字元向量。
# cat() : 將一些字串連接起來,然後將連接後的字串輸出到文件或者是命令列。
>
> args(paste)
function (..., sep = " ", collapse = NULL) # sep : 設定分隔符號,預設為"空格"
NULL
>
>
> args(cat)
function (..., file = "", sep = " ", fill = FALSE, labels = NULL,
append = FALSE)
NULL
> args(paste)
function (..., sep = " ", collapse = NULL)
NULL
>
> # 在"..."後面出現的參數都要明確的指定參數名稱,如下所示:
> paste("a", "b", sep = ":") # 分隔符號為":",表示在連接兩個對象之間要用":"隔開
[1] "a:b"
>
> # 在"..."後面如果沒有完整指定參數名稱,會讓 R 以為該參數的內容也是"..."參數的一部份,如下所示:
> paste("a", "b", se = ":")
[1] "a b :"
>