Missing last sequence in seq() in R
In seq()
, "The second form generates from, from+by, ..., up to the sequence value less than or equal to to." And also since 35280 is not in the requested sequence, it is not returned.
But you can use a calculation in the arguments it you wan to include the next value. Since you know the to
value, assign it a name and use it.
by <- 200
out <- 35280
x <- seq(from = by, to = (out + by - out %% by), by = by)
length(x)
# [1] 177
x[length(x)]
# [1] 35400
If you want to include the to
value, even if it is not in the requested sequence, you can write a little function to add it back on
seqil <- function(..., include.last = TRUE) {
x <- do.call(seq.default, list(...))
if(include.last) c(x, to) else x
}
by <- 200
x <- seqil(from = by, to = 35280, by = by)
tail(x)
# [1] 34400 34600 34800 35000 35200 35280
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