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 containing the original values plus regularly-spaced intervals between each of the values in the old value. This is not difficult.
One strategy is to use a more general function which, given two vectors and a specified by
interval, repeatedly applies seq to pairs of numbers from the two original vectors, using the same by
value. I have not found a built-in function that does this. seq
seems resistant to handling vectors as arguments. Here is a function that performs the more general operation (which I can then use for my immediate need):
multiseq <- function(froms, tos, by){
x <- c();
for (i in seq_along(froms)){
x <- c(x, seq(from=froms[i], to=tos[i], by=by))
}
x
}
For example:
> multiseq(1:2, 1.75:2.75, .25)
[1] 1.00 1.25 1.50 1.75 2.00 2.25 2.50 2.75
(This is just a simple example. What I really want is to do this with an arbitrary sequence, e.g.
-0.89115386 -0.75346155 -0.61576924 -0.47807693 -0.34038463 -0.20269232 -0.06500001 0.07269230 0.21038460 0.34807691 0.48576922 0.62346153 0.76115383
And I want to subdivide each of the intervals into five, to create a new sequence with 5 times as many elements.)
As long as the sequences are not too long, repeatedly extending a vector should not be too slow, I believe. If I need large sequences, I can rewrite to pre-extend the vector and fill it. However, it still bugs me to do this with a loop at all. Is there a more elegant, functional-programming, R-ly way?
Thanks.