[R] complicated sequence with preset length
PIKAL Petr
petr@p|k@| @end|ng |rom prechez@@cz
Tue Oct 12 13:16:04 CEST 2021
Dear all
I know it is quite easy to get a simple seqence by rep function
> c(rep(1:3, 2), rep(4:6,2))
[1] 1 2 3 1 2 3 4 5 6 4 5 6
I could easily get vector of length 24 or 36 using another rep
> rep(c(rep(1:3, 2), rep(4:6,2)),2)
[1] 1 2 3 1 2 3 4 5 6 4 5 6 1 2 3 1 2 3 4 5 6 4 5 6
> length(rep(c(rep(1:3, 2), rep(4:6,2)),2))
[1] 24
> length(rep(c(rep(1:3, 2), rep(4:6,2)),3))
[1] 36
But what about vector of length 30 i.e.
> length(c(rep(c(rep(1:3, 2), rep(4:6,2)),2), rep(1:3,2)))
[1] 30
I know I could make some if construction based on known vector length but is
there a way to use "vector recycling" if I know the desired length and want
to "fill in" the values to get required length vector?
Here is my complicated solution
len <- 30
vec1 <- rep(1:3, 2)
vec2 <- rep(4:6, 2)
base.vec <- c(vec1, vec2)
base.len <- length(c(vec1, vec2))
part <- (len/base.len-trunc(len/base.len))
result <- if (part==0) rep(c(vec1,vec2), len/base.len) else
c(rep(c(vec1,vec2), len/base.len), base.vec[1:(base.len*part)])
Is there any way how to achieve the result by simpler way?
Best regards
Petr
More information about the R-help
mailing list