R語言:if-else條件判斷及any、all、na.omit使用方法

基本結構展示:

if (7<10) {
  print("Seven is less than ten")
} else{
  print("seven is more than ten")
}


 

實例演示:

Titanic=read.csv("https://goo.gl/4Gqsnz")  #從網絡讀取數據

1. any()     #any代表只要有任一值符合,即爲TRUE

if (any(titanicC$Age>70)) {                                              
  print("there are passengers older than 70")
} else{
  print("no one is older than 70")
}


2. all()   #所有都滿足才true

if (all(titanicC$Age>10)) {
  print("all passengers older than 10")
} else{
  print("there are passengers younger than 10")
}


3. na.omit()        #放的位置決定是刪除單一變量缺失值,還是刪除任何變量缺失值

if (any(na.omit(titanic$Age==100))) {
  print("there are passengers aged 100")
} else{
  print("there are no passengers aged 100")
}                                                                                 #數據庫中只要有missing的記錄都刪掉


if (any(titanic$Age==80, na.rm=TRUE)) {
  print("there are passengers aged 80")
} else{
  print("there are no passengers aged 80")
}                                                                               #Age這個變量有missing的記錄刪掉,其他變量有missing可以保留



4.  else if 寫更重複的語句

x=100
y=10
if(x<y){
  print("AA")
} else if(x==y){
  print(BB)
} else{
  print(CC)
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章