欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

R語言中ifelse、which、%in%的用法詳解

 更新時間:2021年04月20日 11:47:49   作者:何同塵  
這篇文章主要介紹了R語言中ifelse、which、%in%的用法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

ifelse、which、%in%是R語言里極其重要的函數(shù),以后會經(jīng)常在別的程序中看到。

ifelse

ifelse是if條件判斷語句的簡寫,它的用法如下:

ifelse(test,yes,no)
參數(shù) 描述
test 一個可以判斷邏輯表達式
yes 判斷為 true 后返回的對象
no 判斷為 flase 后返回的對象

舉例:

x = 5
ifelse(x,1,0)

如果x不等于0,就返回1,等于0就返回0。

which

which 返回條件為真的句柄,給正確的邏輯對象返回一個它的索引。

which(test,arr.ind=FALSE)

test 必須是邏輯對象,邏輯數(shù)組。

舉例:

which(LETTERS == "R")

%in%

%in% 判斷 前面的對象是否在后面的容器中

element %in% list veator
1 %in% c(1:3)

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

基本結(jié)構(gòu)展示:

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

實例演示:

Titanic=read.csv("https://goo.gl/4Gqsnz")  #從網(wǎng)絡(luò)讀取數(shù)據(jù)

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")
}                                                                                 
#數(shù)據(jù)庫中只要有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 寫更重復(fù)的語句

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

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。

相關(guān)文章

最新評論