Search code examples
rseq

Missing last sequence in seq() in R


I have this example data

by<-200
to<-seq(from=by,to=35280,by=by)

Problem is that to ends at 35200 and ignore the last 80 which I need to involve in as last value. Is there any straigthforward way how to achieve it? I have tried along.with and length.out parameters but I cannot go trough.


Solution

  • You can place if statement for the last element of the vector such as in the following function :

    seqlast <- function (from, to, by) 
    {
      vec <- do.call(what = seq, args = list(from, to, by))
      if ( tail(vec, 1) != to ) {
        return(c(vec, to))
      } else {
        return(vec)
      }
    }
    

    Then

    by <- 200
    to <- seqlast(from=by,to=35280,by=by)
    

    will return

    > head(to)
    [1]  200  400  600  800 1000 1200
    > tail(to)
    [1] 34400 34600 34800 35000 35200 35280