在用R語言做各種事物時,用戶自定義函數是不可或缺的。這期來講講如何自定義R的function。首先要介紹的是function的基本框架:
myfunction <- function(arg1, arg2, ... ){ statements return(object) }
- 1
- 2
- 3
- 4
- 函數名稱為myfunction
- arg1,arg2 為參數
- statements 為函數語句
- return(object)返回結果
兩個例子
例子一:隨機數產生,畫圖
function1 <- function(x,y){ plot(x,y) return(x+y) } > x <- rnorm(10) > y <- rnorm(10,2,3) > function1(x,y) [1] 1.5828019 0.2661017 -2.7666838 9.9395144 3.3619610 -0.9452065 -6.4638374 -0.3288615 1.1402272 [10] -0.1285368
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
出結果圖
例子二:判斷、條件句
function2 <- function(x,npar=TRUE,print=TRUE) { if (!npar) { center <- mean(x); spread <- sd(x) } else { center <- median(x); spread <- mad(x) } if (print & !npar) { cat("Mean=", center, "\n", "SD=", spread, "\n") } else if (print & npar) { cat("Median=", center, "\n", "MAD=", spread, "\n") } result <- list(center=center,spread=spread) return(result) } > x<-rnorm(10,0,1) > function2(x) Median= 0.2469624 MAD= 1.161068 $center [1] 0.2469624 $spread [1] 1.161068