2

Say we have the following:

a=c( 1, 9, 5, 7, 8, 11)
length(a) ## 6

and I want to obtain:

a_desired=c( 1, 1, 9, 9, 5, 5, 7, 7, 8, 11)
length(a_desired) ## 10

Basically it stops replicating when it reaches the desired length, in this case 10.

If the desired length is 14,

a_desired=c( 1, 1, 1, 9, 9, 9, 5, 5, 7, 7, 8, 8, 11, 11)

Does anyone have a suggestion on how to obtain this or perhaps a link on something similar asked before ?(I'm not too sure what keyword to look for)

mathnoob
  • 73
  • 1
  • 1
  • 9
  • You might want to say what should happen if the desired length is too long, say 14. – joran Mar 22 '17 at 19:19
  • Thanks for pointing that out; doubling is a poor choice of word I guess. – mathnoob Mar 22 '17 at 19:26
  • This feels like an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) where this is the attempted `y` solution to a problem `x` you do not discuss. Please provide more background as the `rep()` approach may not be needed. – Parfait Mar 22 '17 at 19:43
  • I am trying to extract N number of variables from a subset, but there are only lesser than N possible variables. So to compensate for the missing ones, I am assigning more weight to the existing variables by extracting more of it. It isn't a fair/elegant way considering how they are now weighted differently but it solves my problem. – mathnoob Mar 22 '17 at 19:58

2 Answers2

2

You could write your own function to do something like this

extend_to <- function(x, len) {
    stopifnot(len>0)
    times = len %/% length(x)
    each <- rep(times, length(x))
      more <- len-sum(each)
      if (more>0) {
       each[1:more] <- each[1:more]+1
      }
      rep(x, each)
}


a <- c( 1, 9, 5, 7, 8, 11)
extend_to(a, 6)
# [1]  1  9  5  7  8 11
extend_to(a, 10)
# [1]  1  1  9  9  5  5  7  7  8 11
extend_to(a, 14)
# [1]  1  1  1  9  9  9  5  5  7  7  8  8 11 11
extend_to(a, 2)
# [1] 1 9

We use the rep() to repeat each element a certain number of times.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
0

So if your sequence is currently of length M and you want length N > M, then you have these possibilities:

N <= 2M: double the first (N-M) items

2M < N <= 3M: triple the first (N-2M) items, double the rest

3M < N <= 4M: quadruple the first (N-3M) items, triple the rest.

and so on.

So first, divide the target length by the current length, take the floor, and replicate the sequence that many times. Then add an extra copy of the first remainder items.

a=c( 1, 9, 5, 7, 8, 11)
m=length(a)

n=10 # desired new length

new_a = append(
  rep(a[1:(n%%m)],each=ceiling(n/m)), 
  rep(a[((n%%m)+1):m],each=floor(n/m)))
Mark Reed
  • 91,912
  • 16
  • 138
  • 175