[R] complicated sequence with preset length

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Tue Oct 12 13:27:34 CEST 2021


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



More information about the R-help mailing list