R语言系列:自定义function
在用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