1 控制流
1.1 重复和循环
方式一:for()
for (i in 1:10) print("hello")
方式二:while()
while(i>0){
print("hello")
i<-i-1
}
1.2 条件执行
方式一:if-else结构
if (is.character(roster$grade)) roster$grade<-as.factor(roster$grade)
if (!is.factor(roster$grade)) roster$grade<-as.factor(roster$grade) else print("grade already is a factor")
score<-0.4
ifelse(score>0.5,print("Passed"),print("Failed"))
方式二:switch结构
feel<-c("sad","afraid")
for (i in feel)
print(
switch (i,
happy = "I am glad you are happy",
afraid="There is nothing to fear",
sad="Cheer up",
angry="Clam down"
)
)
3 用户自编函数
3.1 if-else结构自编函数
(1)自定义函数
myfun<-function(x,parametric=T,print=F){
if(parametric){
center<-mean(x);spread<-sd(x)
}else{
center<-median(x);spread<-mad(x) #mad是中位数绝对偏差
}
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)
}
(2)传递参数
set.seed(123) #设置随机种子,保持生成的随机数不变
x<-rnorm(500) #生成500个随机数
y<-myfun(x)
y1<-myfun(x,parametric=F,print=T)