R语言:自定义函数

R语言系列:自定义function

在用R语言做各种事物时,用户自定义函数是不可或缺的。这期来讲讲如何自定义R的function。首先要介绍的是function的基本框架:

myfunction <- function(arg1, arg2, ... ){
statements
return(object)
}
  • 函数名称为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

出结果图

plot图

例子二:判断、条件句

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

总结

看懂这两,基本的函数应该可以实现,稍微复杂的,或别的更加复杂的函数,那就需要经验了。多练习多写代码是实现快速写代码的重要途径!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容