【R】R语言基础-2.控制流

2020-08-27  本文已影响0人  我写的BUG代码少

2. 控制流

重复和循环

for

for (i in 范围){循环体}
for (i in 1:10) {
    print("hahaha")
}
>>>
[1] "hahaha"
[1] "hahaha"
[1] "hahaha"
[1] "hahaha"
[1] "hahaha"
[1] "hahaha"
[1] "hahaha"
[1] "hahaha"
[1] "hahaha"
[1] "hahaha"

while

while (condition){循环体}
i <- 0
while (i < 3) {
    print("hahahha")
    i <- i + 1     #i+=1
}
>>>
[1] "hahahha"
[1] "hahahha"
[1] "hahahha"

【循环练习:斐波那契】

f <- rep(0, 100)
f[1] <- 1
f[2] <- 1
for (i in 3:100) {
    f[i] <- f[i - 1] + f[i - 2]
    print(f[i])
}
f <- rep(0, 100)
f[1] <- 1
f[2] <- 1
i <- 3
while (i <= 100) {
    f[i] <- f[i - 1] + f[i - 2]
    print(f[i])
    i <- i + 1
}

条件执行

If

if(condition) 执行语句
if(condition1) 执行语句1 else 执行语句1
if(condition1) 执行语句1 else if(condition2) 执行语句2 else 执行语句3
#格式一
grades <- c(66, 32, 58, 99)
for (i in 1:length(grades)) {
    if (grades[i] > 60) print("AAA") else print("BBB")
}

#格式二
grades <- c(66, 32, 58, 99)
for (i in 1:length(grades)) {
    if (grades[i] > 60) {
        print("AAA")
    } else {
        print("BBB")
    }
}

switch

switch根据一个表达式的值选择语句执行

switch(expr, ...) # ... 表示与expr的各种可能输出值绑定的语句
feelings <- c("sad", "afraid") 
for (i in feelings) 
    print( 
        switch(i, 
            happy = "I am glad you are happy", 
            afraid = "There is nothing to fear", 
            sad = "Cheer up", 
            angry = "Calm down now" 
        ) 
    )
>>>
[1] "Cheer up" 
[1] "There is nothing to fear"
上一篇 下一篇

猜你喜欢

热点阅读