迭代使用for循环的最佳方法 [英] Best way to iterate using for loop
问题描述
我正在寻找迭代 但是如果时间< - 0,那么我的循环迭代两次,不是零。所以解决方案是: 所以如果我想从 但是如果 我知道我可以检查 澄清 - 我正在寻找类似的解决方案到其他编程语言,如C ++ / Java: R
的最佳方法。我知道简单的解决方案,例如:
$ b $ pre $ times< - 3
for(i in 1:times){
$ b
$ p $ for(i in seq_len(times))
start
到 end $ c
$ p $ for(i in seq_len(end - start))
end-start< 0
然后:
seq_len(-1)
seq_len(-1) :参数必须强制为非负整数
结束开始< 0
在循环之前,但这不是很干净的解决方案...任何其他的想法?
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循环,它创建了正确的向量向量( I'm looking for the best way to iterate in BUT if times <- 0, then my loop iterates twice, not zero. So the solution is: So if I want to iterate from BUT if I know that I can check if To clarify - I'm looking for solution similar to other programming languages, like C++/Java: So if Just write your own helper function 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 ( 这篇关于迭代使用for循环的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!:,
seq_len
, seq_al ong
),你需要担心。 R
. I know simple solutions like:times <- 3
for(i in 1:times){
}
for(i in seq_len(times))
start
to end
:for(i in seq_len(end - start))
end-start < 0
then:seq_len(-1)
Error in seq_len(-1) : argument must be coercible to non-negative integer
end-start < 0
before loop, but this is not very clean solution... any other ideas?for(int i = start; i < end; i++)
start=5
and end=3
the loop doesn't even start.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}
:
,seq_len
, seq_along
) that you need to worry about.