自定义函数的一般格式
myfunction <- function(arg1, arg2, ... )
{ statements return(object) }
实例一:构造计算描述统计量的函数
##自定义函数 mystats()
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") } ##"\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(500)
y<-mystats(x)#输出的就是默认情况
y <- mystats(x, parametric=FALSE, print=TRUE)#相当于对函数的参数进行了设置
实例二:构造日期函数定义为mydate()输出当天的日期
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") ) }#其中cat()函数是当输入的参数不是long或者short的时候给的提示
#验证
mydate("long")
mydate("short")