循环

For 和 While 循环的区别

The while loop keeps executing code until its condition evaluates to FALSE.
The for loop, on the other hand, iterates over a sequence, where a looping variable changes for each iteration, according to the sequence.

while

1. 基本命令

ctr <- 1
while (ctr <= 7) {
  print(paste("ctr is set to ", ctr))
  ctr <- ctr + 1
}

2. break

ctr 能被 5 整除就停止循环。

ctr <- 1
while (ctr <= 7) {
  if (ctr %% 5 == 0) {
    break
  }
  print(paste("ctr is set to ", ctr))
  ctr <- ctr + 1
}

for

1. 基本命令

cities <- c("New York", "Paris", "London", "Tokyo", "Rio de Janeiro", "Cape Town")

for (ci in cities) {
  print(ci)
}

for (i in 1:length(cities)) {
  print(cities[i])
}

条件语句有以上 2 种写法。logs 是一个列表。
如果要修改列表里面的内容,只能使用后一种方法
Using the for (log in logs) approach here won’t work, because log is a local copy of an element in logs. To actually access and change the elements in the logs list, you will need to use the looping index.

2. break

for (ci in cities) {
  if (nchar(ci) == 6){
    break
  }
  print(ci)
}

3. next

for (ci in cities) {
  if (nchar(ci) == 6){
    next
  }
  print(ci)
}

reference

https://campus.datacamp.com/courses/intermediate-r-practice

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值