Elegant way to vectorize seq?

后端 未结 3 1921
醉酒成梦
醉酒成梦 2021-01-13 03:50

Despite the similar title, this is not the same question as Vectorizing rep and seq in R.

My immediate goal: Given a vector, I want to generate a new vector containi

3条回答
  •  感情败类
    2021-01-13 04:49

    Try following

    x <- c(1, 2, 4, 8)
    y <- unlist(mapply(FUN = function(from, to) {
        seq(from = from, to = to, by = 0.25)
    }, head(x, -1), tail(x, -1)))
    y
    ##  [1] 1.00 1.25 1.50 1.75 2.00 2.00 2.25 2.50 2.75 3.00 3.25 3.50 3.75 4.00 4.00 4.25 4.50 4.75 5.00 5.25 5.50 5.75 6.00
    ## [24] 6.25 6.50 6.75 7.00 7.25 7.50 7.75 8.00
    
    result <- y[!duplicated(y)]
    result
    ##  [1] 1.00 1.25 1.50 1.75 2.00 2.25 2.50 2.75 3.00 3.25 3.50 3.75 4.00 4.25 4.50 4.75 5.00 5.25 5.50 5.75 6.00 6.25 6.50
    ## [24] 6.75 7.00 7.25 7.50 7.75 8.00
    

提交回复
热议问题