溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

R語(yǔ)言中ifelse、which、%in%怎么用

發(fā)布時(shí)間:2021-04-30 14:16:19 來(lái)源:億速云 閱讀:518 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)R語(yǔ)言中ifelse、which、%in%怎么用的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。

什么是R語(yǔ)言

R語(yǔ)言是用于統(tǒng)計(jì)分析、繪圖的語(yǔ)言和操作環(huán)境,屬于GNU系統(tǒng)的一個(gè)自由、免費(fèi)、源代碼開(kāi)放的軟件,它是一個(gè)用于統(tǒng)計(jì)計(jì)算和統(tǒng)計(jì)制圖的優(yōu)秀工具。

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

ifelse

ifelse是if條件判斷語(yǔ)句的簡(jiǎn)寫(xiě),它的用法如下:

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

舉例:

x = 5
ifelse(x,1,0)

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

which

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

which(test,arr.ind=FALSE)

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

舉例:

which(LETTERS == "R")

%in%

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

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

補(bǔ)充:R語(yǔ)言: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")
}

實(shí)例演示:

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

1. any()

#any代表只要有任一值符合,即為T(mén)RUE
if (any(titanicC$Age>70)) {                                              
  print("there are passengers older than 70")
} else{
  print("no one is older than 70")
}

2. all()

#所有都滿(mǎn)足才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ù)庫(kù)中只要有missing的記錄都刪掉
if (any(titanic$Age==80, na.rm=TRUE)) {
  print("there are passengers aged 80")
} else{
  print("there are no passengers aged 80")
}       
#Age這個(gè)變量有missing的記錄刪掉,其他變量有missing可以保留

4. else if 寫(xiě)更重復(fù)的語(yǔ)句

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

感謝各位的閱讀!關(guān)于“R語(yǔ)言中ifelse、which、%in%怎么用”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI