Missing last sequence in seq() in R

后端 未结 5 1060
感动是毒
感动是毒 2021-01-13 13:10

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

5条回答
  •  爱一瞬间的悲伤
    2021-01-13 14:14

    Whilst not solving the exact issue raised my preferred solution to this is to extend the sequence to add an additional value so that the to value is included in the sequence rather than just appending the to value at the end. This builds on the answers by both @djas and @Etienne Kintzler.

    seq0 <- function(from = 1, to = 1, by = 1, incLast = TRUE){
        out = do.call(what = seq, args = list(from, to, by))
        if (incLast & to%%by != 0){
            out = c(out, tail(out, 1) + by) 
        } 
        return(out)
    }
    

    Example outputs:

    > seq0(from = 0, to = 20, by = 6, incLast = FALSE)
    [1]  0  6 12 18
    > seq0(from = 0, to = 20, by = 6, incLast = TRUE)
    [1]  0  6 12 18 24
    > seq0(from = 0, to = -20, by = -6, incLast = FALSE)
    [1]   0  -6 -12 -18
    > seq0(from = 0, to = -20, by = -6, incLast = TRUE)
    [1]   0  -6 -12 -18 -24
    

提交回复
热议问题