迭代使用for循环的最佳方法 [英] Best way to iterate using for loop

查看:138
本文介绍了迭代使用for循环的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找迭代 R 的最佳方法。我知道简单的解决方案,例如:
$ b $ pre $ times< - 3
for(i in 1:times){






$ b

但是如果时间< - 0,那么我的循环迭代两次,不是零。所以解决方案是:

$ p $ for(i in seq_len(times))

所以如果我想从 start end
$ p $ for(i in seq_len(end - start))

但是如果 end-start< 0 然后:

  seq_len(-1)
seq_len(-1) :参数必须强制为非负整数

我知道我可以检查结束开始< 0 在循环之前,但这不是很干净的解决方案...任何其他的想法?

澄清 - 我正在寻找类似的解决方案到其他编程语言,如C ++ / Java:

pre code> for(int i = start; i< end; i ++)$ b所以如果 start = 5 和<$ c $

解决方案

只要写你自己的帮手函数

  loop_seq < - 函数(start,end){
if(end< start)return(integer 0))
seq(start,end)
}

for(i in loop_seq(3,4)){print(i)}
#[1 (3)中的(i in loop_seq(3,3)){print(i)}
#[1] 3
(3,2)){print(i)}
#{nothing}

for循环总是迭代一个向量,所以问题实际上不是for循环,它创建了正确的向量向量(:, seq_len seq_al ong ),你需要担心。

I'm looking for the best way to iterate in R. I know simple solutions like:

times <- 3
for(i in 1:times){

}

BUT if times <- 0, then my loop iterates twice, not zero. So the solution is:

for(i in seq_len(times))

So if I want to iterate from start to end :

for(i in seq_len(end - start))

BUT if end-start < 0 then:

seq_len(-1)
Error in seq_len(-1) : argument must be coercible to non-negative integer

I know that I can check if end-start < 0 before loop, but this is not very clean solution... any other ideas?

To clarify - I'm looking for solution similar to other programming languages, like C++/Java:

for(int i = start; i < end; i++)

So if start=5 and end=3 the loop doesn't even start.

解决方案

Just write your own helper function

loop_seq <- function(start,end) {
    if(end<start) return(integer(0))
    seq(start, end)
}

for(i in loop_seq(3,4)) {print(i)}
# [1] 3
# [1] 4
for(i in loop_seq(3,3)) {print(i)}
# [1] 3
for(i in loop_seq(3,2)) {print(i)}
# {nothing}

The for loop will always iterate over a vector, so the problem really isn't the for loop, it's creating the right vector of indexes (:,seq_len, seq_along) that you need to worry about.

这篇关于迭代使用for循环的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆