5

When we want a sequence in R, we use either construction:

> 1:5
[1] 1 2 3 4 5
> seq(1,5)
[1] 1 2 3 4 5

this produces a sequence from start to stop (inclusive) is there a way to generate a sequence from start to stop (exclusive)? like

[1] 1 2 3 4 

Also, I don't want to use a workaround like a minus operator, like:

seq(1,5-1)

This is because I would like to have statements in my code that are elegant and concise. In my real world example the start and stop are not hardcoded integers but descriptive variable names. Using the variable_name -1 construction just my script uglier and difficult to read for a reviewer.

PS: The difference between this question and the one at remove the last element of a vector is that I am asking for sequence generation while the former focuses on removing the last element of a vector Moreover the answers provided here are different and relevant to my problem

Kay
  • 799
  • 1
  • 11
  • 29
  • 5
    Does this answer your question? [remove the last element of a vector](https://stackoverflow.com/questions/12114439/remove-the-last-element-of-a-vector) – slava-kohut Jul 10 '20 at 12:26
  • "Also, I don't want to use a workaround like a minus operator, like:". Please, clarify why not and which kind of solutions you like. – pasaba por aqui Jul 12 '20 at 08:56

2 Answers2

4

One possible solution would be

head(1:5, -1)
# [1] 1 2 3 4

or you could define your own function

seq_last_exclusive <- function(x) return(x[-length(x)])
seq_last_exclusive(1:5)
# [1] 1 2 3 4
Ric S
  • 9,073
  • 3
  • 25
  • 51
3

We can use the following function

f <- function(start, stop, ...) {
  if(identical(start, stop)) {
    return(vector("integer", 0))
  }
  seq.int(from = start, to = stop - 1L, ...)
}

Test

f(1, 5)
# [1] 1 2 3 4

f(1, 1)
# integer(0)
markus
  • 25,843
  • 5
  • 39
  • 58