R语言笔记二(控制结构)

Control Structures

Control structures in R allow you to control the flow of execution of the program, depending on runtime conditions. Common structures are

  • if, else: testing a condition
  • for: execute a loop a fixed number of times
  • while: execute a loop while a condition is true
  • repeat: execute an infinite loop
  • break: break the execution of a loop
  • next: skip an interation of a loop
  • return: exit a function

    Most control structures are not used in interactive sessions, but rather when writing functions or longer expresisons.

if

if(<condition>) {
         ## do something
} else { 
         ## do something else
}
if(<condition1>) {
         ## do something
} else if(<condition2>) {
         ## do something different
} else {
         ## do something different
}

This is a valid if/else structure.

if(x > 3) {
        y <- 10
} else {
        y <- 0
}

So is this one.

y <- if(x > 3) {
          10
} else {
          0
}

Of course, the else clause is not necessary.

if(<condition1>) {
}
if(<condition2>) {
}

for

for loops take an integrator variable(积分变量) and assign it successive values(连续值) from a sequence or vector. For loops are most commonly used for iterating over(迭代) the elements of an object (list, vector, etc.)

for(i in 1:10) {
    print(i)
}

This loop takes the i variable and in each iteration of the loop gives it values 1, 2, 3, …, 10, and then exits.

These three loops have the same behavior.

x <- c("a", "b", "c", "d")
for(i in 1:4) {
          print(x[i])
}
for(i in seq_along(x)) {   ## seq_along()
          print(x[i])
}
for(letter in x) {
          print(letter)
}
for(i in 1:4) print(x[i])

Nested for loops 嵌套循环

for loops can be nested.

x <- matrix(1:6, 2, 3)

for(i in seq_len(nrow(x))) {
         for(j in seq_len(ncol(x))) {
                  print(x[i, j])
    }
}

Be careful with nesting though. Nesting beyond 2–3 levels is often very difficult to read/understand.

while

While loops begin by testing a condition. If it is true, then they execute the loop body. Once the loop body is executed, the condition is tested again, and so forth.

count <- 0
while(count < 10) {
        print(count)
        count <- count + 1
}

While loops can potentially result in infinite loops if not written properly. Use with care!

Sometimes there will be more than one condition in the test.

z <- 5
while(z >= 3 && z <= 10) {
         print(z)
         coin <- rbinom(1, 1, 0.5)
         
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值