R语言中用户自编函数

R语言中用户自编函数

1、测试1

mystat <- function(x, parametric = TRUE, print = FALSE){
  if(parametric){
    center = mean(x);
    spread = sd(x)
  } else
  {
    center = median(x);
    spread = mad(x)
  }
  if(parametric & print){
    cat("center= ", center,"\n","spread =", spread,"\n")
  } else
    if(!parametric & print){
      cat("median= ", center, "\n","mad= ", spread, "\n")
    }
  result = list(center, spread)
  return(result)
}
a <- 1:5
y <- mystat(a)
y <- mystat(a,print = T)
y <- mystat(a,parametric = F, print = T)

2、测试2

mydate <- function(type = "long"){
  switch (type,
    long = format(Sys.time(), "%A %B %D %Y"),
    short = format(Sys.time(), "%y-%m-%d"),
    cat(type, "is not recognized type!")
  )
}
mydate()
mydate("long")
mydate("short")
mydate("median")

原文地址:https://www.cnblogs.com/liujiaxin2018/p/14699537.html