Reputation: 307
I'm interested in creating a vector of sequences, all from 0 to 1, but with varying "by" arguments to seq( ).
I start with a vector I'm hoping to use for the "by" argument:
x <- c(3,6,3,9,10)
I'm wanting this to be the input to the seq( ) function:
seq(0, 1, by = 1/(x-1))
So for the first few elements of the vector it would be:
seq(0, 1, by = 1 / (3 - 1))
seq(0, 1, by = 1 / (6 -1))
Yielding vectors like:
0.0 0.5 1.0
0.0 0.2 0.4 0.6 0.8 1.0
Ultimately, I'd like the output to be a long vector that includes all of these sequences of varying lengths. Maybe a job for a loop? Or sapply / lapply?
Upvotes: 0
Views: 147
Reputation: 20811
Another way: I use seq.default
since you need to vectorize the by
argument
x <- c(3,6,3,9,10)
vseq <- Vectorize(seq.default)
vseq(0, 1, by = 1/(x-1))
# [[1]]
# [1] 0.0 0.5 1.0
#
# [[2]]
# [1] 0.0 0.2 0.4 0.6 0.8 1.0
#
# [[3]]
# [1] 0.0 0.5 1.0
#
# [[4]]
# [1] 0.000 0.125 0.250 0.375 0.500 0.625 0.750 0.875 1.000
#
# [[5]]
# [1] 0.0000000 0.1111111 0.2222222 0.3333333 0.4444444 0.5555556 0.6666667 0.7777778
# [9] 0.8888889 1.0000000
Upvotes: 2
Reputation: 3622
Here's what the code would be for an example x = 1000
vector_x <- c()
for(i in 1:1000){
x <- seq(0, 1, by = 1/(i-1))
vector_x <- c(vector_x, x)
}
vector_x
Upvotes: 0
Reputation: 44614
sapply(1/(x-1), seq, from=0, to=1)
[[1]]
[1] 0.0 0.5 1.0
[[2]]
[1] 0.0 0.2 0.4 0.6 0.8 1.0
[[3]]
[1] 0.0 0.5 1.0
[[4]]
[1] 0.000 0.125 0.250 0.375 0.500 0.625 0.750 0.875 1.000
[[5]]
[1] 0.0000 0.1111 0.2222 0.3333 0.4444 0.5556 0.6667 0.7778 0.8889 1.0000
Upvotes: 4