R作為一門編程語言,可以自行編寫函數(shù),很合理吧。
function自編函數(shù)
R中的許多函數(shù)都是包含了已有函數(shù)??匆幌伦孕芯帉懞瘮?shù)的的語句基本結(jié)構(gòu):
funname <- function(arg1, arg2, arg3, ...) {
statements
return(object)
}
函數(shù)可以添加默認參數(shù)。函數(shù)中的對象只在函數(shù)內(nèi)部使用。 也可以用return函數(shù)返回R對象,返回對象的數(shù)據(jù)類型是任意的, 從標量到列表皆可。
繼續(xù)在使用例子中進行學(xué)習(xí),使用書中的例子,編寫一個函數(shù), 用來計算數(shù)據(jù)對象的集中趨勢和散布情況。 此函數(shù)應(yīng)當可以選擇性地給出參數(shù)統(tǒng)計量(均值和標準差) 和非參數(shù)統(tǒng)計量(中位數(shù)和絕對中位差) 。
mystats <- function(x, parametric=TRUE, print=FALSE) {
if (parametric) {
center <- mean(x); spread <- sd(x)
} else {
center <- median(x); spread <- mad(x)
}
if (print & parametric) {
cat("Mean=", center, "\n", "SD=", spread, "\n")
} else if (print & !parametric) {
cat("Median=", center, "\n", "MAD=", spread, "\n")
}
result <- list(center=center, spread=spread)
return(result)
}
> set.seed(1234)
> x <- rnorm(50)
> mystats(x)
$center
[1] -0.453053
$spread
[1] 0.8850435
說明一下,parametric=TRUE默認值為真,為真則計算平均值和方差; print=FALSE默認值為假,即不打印cat中的內(nèi)容;return(result)函數(shù)表示返回一個列表對象,包含輸入數(shù)據(jù)的集中趨勢和離散趨勢統(tǒng)計結(jié)果。
使用switch結(jié)構(gòu)
同樣引用書中的例子,輸入當天的日期,格式選擇或長或短,默認為長格式。
mydate <- function(type="long") {
switch(type,
long = format(Sys.time(), "%A %B %d %Y"),
short = format(Sys.time(), "%m-%d-%y"),
cat(type, "is not a recognized type\n")
)
}
> mydate("long")
[1] "星期日 八月 13 2023"
> mydate("none")
none is not a recognized type
type有兩個參數(shù)可選,long和 short;如果是其他值,就會輸出cat函數(shù)中的內(nèi)容用來提示錯誤輸入的參數(shù)值信息。
函數(shù)warning()可以生成一條錯誤提示信息,message() 可以生成一條診斷信息, 或用stop()停止當前表達式的執(zhí)行并提示錯誤。