Elegant way to vectorize seq?

后端 未结 3 1903
醉酒成梦
醉酒成梦 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
    
    0 讨论(0)
  • 2021-01-13 04:49

    As @TylerRinker suggested in a comment on my question, for my particular needs there's a solution that's simpler than what's suggested by my formulation of the problem--I was too focused on a particular way of thinking about it. Since I want regularly spaced numbers interpolated between numbers that are already regularly spaced, I can just apply seq to the initial and terminal values in the vector, using a by value that divides evenly into the interval between values in the the original vector:

    subdiv <- function(x, by) seq(x[1], x[length(x)], by)
    subdiv(1:4, .25)
    [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
    subdiv(c(-0.20269232, -0.06500001,  0.07269230), 0.1376923/3)
    [1] -0.20269232 -0.15679489 -0.11089745 -0.06500002 -0.01910259  0.02679485  0.07269228
    

    where 0.1376923 is the difference between successive elements in the second application. This solution is OK as long as I don't need that the elements carried over from the original vector to be exactly equal to their original values--as you can see, there are some differences due to floating point arithmetic. (What I'm actually doing is constructing bins for histograms; the precise boundaries won't matter.)

    @dickoa's and @geektrader's answers have broader use, though, and preserve the exact values of the original numbers from the input vector.

    0 讨论(0)
  • 2021-01-13 04:51

    In R, one of the easiest way to vectorize a function is to use the Vectorize function.

    Basically, you can vectorize the from an to argument and give all the starter as a vector in the from argument and do the same thing for the to argument.

    Using your example, you can do something like this

    seq2 <- Vectorize(seq.default, vectorize.args = c("from", "to"))
    
    unlist(seq2(from = c(1, 1.75), to = c(2, 2.75), by = 0.25))
    
    ## [1] 1.00 1.25 1.50 1.75 2.00 1.75 2.00 2.25 2.50 2.75
    
    0 讨论(0)
提交回复
热议问题