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

一、循环与控制

循环:

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

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

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

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

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 ")) } mydate("long") mydate("short") mydate() mydate("medium")

经验分享 程序员 微信小程序 职场和发展