Search code examples
rincrementseq

seq() with changing increment of sequence


Let's say I want to create a sequence with base R's seq() from 1 to 15. Is there a way that an increment of 1 applies for the values 1 to 10 and 12 to 15 but an increment of .1 applies from 10.1 to 11.9? Basically, I'm interested in how to combine the three sequences seq(1,10,1), seq(10.1,11.9,0.1), seq(12,15,0.1) into one seq()


Solution

  • If the idea is just to get a compact expression then try any of these. s5, in particular, seems close to what you are looking for, viz. a vectorized seq. No packages are used.

    s1 <- c(1:10, 101:119 / 10, 12:15 )
    
    s2 <- cumsum(rep(c(1, 0.1, 1), c(10, 20, 3)))
    
    s3 <- unlist(Map(seq, c(1, 10.1, 12), c(10, 11.9, 15), c(1, 0.1, 1)))
    
    s4 <- Filter(function(x) (x %% 10 == 0) | (x > 100 & x < 120), 10:150) / 10
    
    s5 <- sequence(nvec = c(10, 20, 3), from = c(10, 101, 130), by = c(10, 1, 10)) / 10
    
    # check
    all.equal(s1, s2, s3, s4, s5)
    ## [1] TRUE