R語言--控制流和自定義函數(if、else、while、switch)


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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM