The R code
n = 0
for (i in 1:n) {
cat("\nhello")
}
prints hello
once, which is also the output when n = 1. What is the idiomatic way to write a loop whose body is not executed if n = 0?
The R code
n = 0
for (i in 1:n) {
cat("\nhello")
}
prints hello
once, which is also the output when n = 1. What is the idiomatic way to write a loop whose body is not executed if n = 0?
We need seq_along
(if it is a sequence) or seq_len
(if it is a single value)
n <- 0
for(i in seq_len(n))
cat("\nhello")
The case when seq_along
should be used when we expect the vector/list etc to have length
more than 1
> n1 <- c(5, 3, 5)
> seq_len(n1)
[1] 1 2 3 4 5
Warning message:
In seq_len(n1) : first element used of 'length.out' argument
> seq_along(n1)
[1] 1 2 3
Other case when we have a length of 0
> n1 <- integer(0)
> # n1 <- NULL
> n1
integer(0)
> seq_along(n1)
integer(0)
> seq_len(n1)
Error in seq_len(n1) : argument must be coercible to non-negative integer
In addition: Warning message:
In seq_len(n1) : first element used of 'length.out' argument
Thus, there is no perfect solution that works for all cases. It may depend upon the input