18.1 顺序结构

18.2 分支结构

18.2.1 if() 和 else

Show the code
x <- 10

if(x %%3 ==0) {
    message("能被3整除")
} else {
    message("不能被3整除")
}

18.2.2 ifelse()

Show the code
x <- c(10,9)
ifelse(x %%3 ==0,"能被3整除","不能被3整除")
#> [1] "不能被3整除" "能被3整除"
if_else(x %%3 ==0,"能被3整除","不能被3整除")
#> [1] "不能被3整除" "能被3整除"

18.2.3 case_when()

Show the code
x <- 1:10
dplyr::case_when(
  x %% 35 == 0 ~ "fizz buzz",
  x %% 5 == 0 ~ "fizz",
  x %% 7 == 0 ~ "buzz",
  is.na(x) ~ "???",
  TRUE ~ as.character(x)
)
#>  [1] "1"    "2"    "3"    "4"    "fizz" "6"    "buzz" "8"    "9"    "fizz"

18.2.4 switch()

Show the code
# 如果多个输入具有相同的输出,则可以将右侧留空,输入将“掉入”到下一个值。这模仿了 C 语句的行为
nlegs <- function(x) {
  switch(x,
    cow = ,
    horse = ,
    dog = 4,
    human = ,
    chicken = 2,
    plant = 0,
    stop("Unknown input")  #最后应该始终抛出错误,否则不匹配的输入将返回 NULL
  )
}
nlegs("cow")
#> [1] 4

nlegs("do6")
#> Error in nlegs("do6"): Unknown input

18.3 循环结构

18.3.1 for

Show the code
for(i in 1:5){
    print(1:i)
}
#> [1] 1
#> [1] 1 2
#> [1] 1 2 3
#> [1] 1 2 3 4
#> [1] 1 2 3 4 5
Show the code
for (i in 1:10) {
  if (i < 3) 
    next  # 退出当前迭代,后面不执行了

  print(i)
  
  if (i >= 5)
    break # 退出整个循环
}
#> [1] 3
#> [1] 4
#> [1] 5

18.3.2 while()

Show the code
i <- 0
while(i<=10){
    print(i)
    i=i+1
}
#> [1] 0
#> [1] 1
#> [1] 2
#> [1] 3
#> [1] 4
#> [1] 5
#> [1] 6
#> [1] 7
#> [1] 8
#> [1] 9
#> [1] 10
Show the code
flag <- TRUE
x <- 0
i <- 0
while(flag){
    x <- x+1
    if(x%%3==0) {
        i <- i+1
        print(x)
    }
    if(i==25) flag <- FALSE
}
#> [1] 3
#> [1] 6
#> [1] 9
#> [1] 12
#> [1] 15
#> [1] 18
#> [1] 21
#> [1] 24
#> [1] 27
#> [1] 30
#> [1] 33
#> [1] 36
#> [1] 39
#> [1] 42
#> [1] 45
#> [1] 48
#> [1] 51
#> [1] 54
#> [1] 57
#> [1] 60
#> [1] 63
#> [1] 66
#> [1] 69
#> [1] 72
#> [1] 75

18.3.3 repeat()

Show the code
i <- 1

repeat{
  print(i)
  i <- i*2
  if (i > 100) break  # 跳出当前的循环
}
#> [1] 1
#> [1] 2
#> [1] 4
#> [1] 8
#> [1] 16
#> [1] 32
#> [1] 64
Show the code
i <- 1

repeat{
  print(i)
  i <- i*2
  if (i > 200) break()
  if (i > 100) next()  #跳过后续代码的运行进入下一次循环
  print("Can you see me?")
}
#> [1] 1
#> [1] "Can you see me?"
#> [1] 2
#> [1] "Can you see me?"
#> [1] 4
#> [1] "Can you see me?"
#> [1] 8
#> [1] "Can you see me?"
#> [1] 16
#> [1] "Can you see me?"
#> [1] 32
#> [1] "Can you see me?"
#> [1] 64
#> [1] 128