R语言中如何编写自己的函数初步入门

时间:2025-02-15 07:12:31

一、循环与控制

循环:

for(i in 1:10) print("hello world")

i<-10

while(i>0){

print(i);

i<-i-1;

}

控制

if()

if() else

ifelse(判断,true,false)

switch(type,。。。)

二、用户自定义函数

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")
  } else if (print & !parametric) {
    cat("Median=", center, "\n", "MAD=", spread, "\n")
  }
  result <- list(center=center, spread=spread)
  return(result)
}


如何调用我们自己编写的函数

(1234)
x <- rnorm(500) 生成符合正态分布500个元素
y <- mystats(x)
y <- mystats(x, parametric=FALSE, print=TRUE)


下面是一个关于switch函数的例子

mydate <- function(type="long") {
    switch(type,
    long =  format((), "%A %B %d %Y"), 
    short = format((), "%m-%d-%y"),
    cat(type, "is not a recognized type\n"))
}
mydate("long")
mydate("short")
mydate()
mydate("medium")