R語言:for循環使用小結

基本結構展示:

vals =c(5,6,7)

for(v in vals){
  print(v)
}

#即把大括號裏的內容對vals裏的每一個值都循環run一遍


實例展示:

1. paste() 命令是把幾個字符連接起來,如paste("A","B","C",sep=" ")得到的就是“A B C”,在次基礎上寫如下for loop:

partnumber = c(1,2,5,78)
for(i in partnumber){
 print(paste("participant number",i, sep = " ")) 
}

#就可以得到一串參與者號碼,根據上面給定的幾個值, 從"participant number 1" 到"participant number 8" 


2. 雙重loop

partnumber = c(1,2,5,78)
institution =c("cancer center", "RMH", "Florey")
for(i in partnumber){
  for(j in institution){
  print(paste("participant number",i,", institution",j,sep = " "))
}

}

# 先對j循環,後對i循環,得到如下結果

[1] "participant number 1 , institution cancer center"
[1] "participant number 1 , institution RMH"
[1] "participant number 1 , institution Florey"
[1] "participant number 2 , institution cancer center"
[1] "participant number 2 , institution RMH"
[1] "participant number 2 , institution Florey"
[1] "participant number 5 , institution cancer center"
[1] "participant number 5 , institution RMH"
[1] "participant number 5 , institution Florey"
[1] "participant number 78 , institution cancer center"
[1] "participant number 78 , institution RMH"
[1] "participant number 78 , institution Florey"

# 兩個loop的話,output得放最中心的loop裏面,如果只要要第一層loop,就放在靠外一層括號裏面,第二層括號就保留最後的一個值



3. 數據庫實例演示

 Titanic=read.csv("https://goo.gl/4Gqsnz")  #從網絡讀取數據<0.2, 0.2-0.6還是>0.6。

目的:看不同艙位(Pclass)和不同性別(Sex)的人的生存率是

A<- sort(unique(Pclass))   #sort可以把類別按大小順序排,unique()命令是把分類變量的種類提取出來
B<- sort(unique(Sex))


for(i in A){ 
  for(j in B){
   if(mean(Survived[Pclass==i&Sex==j])<0.2){
    print(paste("for class",i,"sex",j,"mean survival is less than 0.2"))
  } else if (mean(Survived[Pclass==i&Sex==j])>0.6){
    print(paste("for class",i,"sex",j,"mean survival is more than 0.6"))
  } else {
    print(paste("for class",i,"sex",j,"mean survival is between 0.2 and 0.6"))}
 
  }
  
}


結果如下:

[1] "for class 1 sex female mean survival is more than 0.6"
[1] "for class 1 sex male mean survival is between 0.2 and 0.6"
[1] "for class 2 sex female mean survival is more than 0.6"
[1] "for class 2 sex male mean survival is less than 0.2"
[1] "for class 3 sex female mean survival is between 0.2 and 0.6"
[1] "for class 3 sex male mean survival is less than 0.2"



發佈了30 篇原創文章 · 獲贊 67 · 訪問量 36萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章