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

R語(yǔ)言中循環(huán)的相關(guān)知識(shí)詳解

 更新時(shí)間:2023年03月16日 09:00:18   作者:微小冷  
這篇文章主要為大家詳細(xì)介紹了R語(yǔ)言中循環(huán)的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)R語(yǔ)言有一定的幫助,感興趣的可以了解一下

repeat

repeat是最存粹的循環(huán),只要不讓出來(lái),就一直重復(fù){}中的代碼,可以在命令行中輸入

repeat{print("hello r")}

然后就會(huì)看到命令行瘋狂地刷新,輸出hello r。這個(gè)時(shí)候不用擔(dān)心,只需點(diǎn)擊命令行右上角出現(xiàn)的紅色的stop按鈕,就可以中斷輸出了。

為了讓repeat能跳出循環(huán),可以采用break關(guān)鍵字。例如,想輸出5次hello r,可以寫(xiě)為

i = 0
repeat{
    if(i==5){break}
    i <- i + 1
    print("hello r")
}

這樣就剛好輸出5次,效果如下

> repeat{
+     if(i==5){break}
+     i <- i + 1
+     print("hello r")
+ }
[1] "hello r"
[1] "hello r"
[1] "hello r"
[1] "hello r"
[1] "hello r"

while

和repeat相比,while循環(huán)直接包含了循環(huán)條件,當(dāng)不滿足這個(gè)條件時(shí),可以自動(dòng)跳出

i = 0
while(i<5){
    i <- i+1
    print("hello r")}

其中i<5就是循環(huán)條件。這種寫(xiě)法比repeat...break簡(jiǎn)潔了許多,但效果是相同的

> i = 0
> while(i<5){
+     i <- i+1
+     print("hello r")}
[1] "hello r"
[1] "hello r"
[1] "hello r"
[1] "hello r"
[1] "hello r"

向量

在介紹for循環(huán)之前,有必要介紹一下向量。向量可以理解為數(shù)的組合,是R語(yǔ)言處理較多數(shù)據(jù)時(shí)的基礎(chǔ)數(shù)據(jù)結(jié)構(gòu),其創(chuàng)建方法為c(),示例如下

> c1 <- c(1,2,3,4,5)
> c2 <- c(1:5)
> print(c1)
[1] 1 2 3 4 5
> print(c2)
[1] 1 2 3 4 5

這兩個(gè)數(shù)組的內(nèi)容貌似完全相同,從而可以理解1:5的作用就是生成1到5的所有自然數(shù)。但在Environment中,c1的值為num [1:5] 1 2 3 4 5;c2的值卻為int [1:5] 1 2 3 4 5。num和int是數(shù)據(jù)類(lèi)型的標(biāo)識(shí),int標(biāo)識(shí)整型;num表示實(shí)數(shù)類(lèi)型。

換言之,在R語(yǔ)言中,直接寫(xiě)出的1,2,..均為number類(lèi)型,而經(jīng)由c(1:5)創(chuàng)建的向量,則為整型的。

for循環(huán)

在有了向量的概念之后,就可以較為方便地理解for循環(huán)了,示例如下

for(i in c(1:5)){
    print("hello r")
}

這同樣是一個(gè)打印5次hello r的例子,但使用的是for循環(huán),其中i in c(1:5)表示將i從1,2,3,4,5中依次拿出,每拿出一個(gè)數(shù),就循環(huán)一次,所有數(shù)拿完了,就結(jié)束循環(huán)。

這種寫(xiě)法比while還要簡(jiǎn)潔,但依舊可以實(shí)現(xiàn)相同的效果

> for(i in c(1:5)){
+     print("hello r")
+ }
[1] "hello r"
[1] "hello r"
[1] "hello r"
[1] "hello r"
[1] "hello r"

break和next

前面提到,在repeat中,只有通過(guò)break才能跳出循環(huán)。在while和for中,雖然都有自己的結(jié)束循環(huán)的方法,但break這個(gè)關(guān)鍵字仍然適用。例如,想要打印10以內(nèi),所有平方小于10的數(shù)

> for(i in c(1:10)){
+     if(i^2>10){break}
+     print(i^2)
+ }
[1] 1
[1] 4
[1] 9

除了break,next這個(gè)關(guān)鍵字也可以起到循環(huán)控制的作用,其效果為跳過(guò)某一次循環(huán),例如,相對(duì)10以內(nèi)的所有奇數(shù)做一系列列的操作,常規(guī)寫(xiě)法是

for(i in c(1:10)){
    if(i%%2!=0){
        .....
    }
}

但這種寫(xiě)法將處理流程嵌入了新的層級(jí)之中,并不優(yōu)雅,這個(gè)時(shí)候可用next來(lái)跳過(guò)不符合要求的情況,示例如下

> for(i in c(1:10)){
+     if(i%%2==0){next}
+     print(i^2+sin(i))
+ }
[1] 1.841471
[1] 9.14112
[1] 24.04108
[1] 49.65699
[1] 81.41212

到此這篇關(guān)于R語(yǔ)言中循環(huán)的相關(guān)知識(shí)詳解的文章就介紹到這了,更多相關(guān)R語(yǔ)言 循環(huán)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論