On 12/10/2021 7:16 a.m., PIKAL Petr wrote:
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?


You can use the length.out argument to repeat the input as often as necessary, e.g.

 rep(c(rep(1:3, 2), rep(4:6,2)), length.out = 30)
 #>  [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 1 2 3 1 2 3

Duncan Murdoch
Duncan Murdoch

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to