1

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?

Fortranner
  • 2,525
  • 2
  • 22
  • 25
  • 1
    R, for some arcane design reason, decides that 1:0 creates a sequence counting down. You need to use `seq_along` to generate what you want. Also apparently don't use `seq` alone, because that one is [broken](https://stackoverflow.com/questions/13732062/what-are-examples-of-when-seq-along-works-but-seq-produces-unintended-results). – ifly6 Jul 15 '21 at 19:02

2 Answers2

3

You should use seq_len

n = 0
for (i in seq_len(n)) {
   cat("\nhello")
}
Onyambu
  • 67,392
  • 3
  • 24
  • 53
1

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

akrun
  • 874,273
  • 37
  • 540
  • 662