控制流
一、循环结构
- for结构
for (var in seq) statement - while结构
while (cond) statement
二、条件结构
- if-else结构
if (cond) statement
if (cond) statement1 else statement2 - ifelse结构
ifelse(cond,statement1,statement2) - switch结构
根据一个表达式的值选择语句执行。
feelings<-c("sad","afraid")
for (i in feelings)
print(
switch(i,
happy="glad you are happy.",
afraid="Don't be scard",
sad="Cheer up!"
)
)
自编函数
语法规则
myfunction<-function(arg1,arg2,…){
statements
return(object)
}
代码示例:
mystats<-function(x,parametric=TRUE,print=FALSE){
if (parametric) {
center<-mean(x);spread<-sd(x)
} else {
center<-median(x);spread<-mad(x)
}
if (print¶metric){
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)
}
set.seed(1234)
x<-rnorm(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\n")
)
}
mydate("short")
mydate("medium")