8

I would like to create a sequence from two numbers, such that the occurrence of one of the numbers decreases (from n_1 to 1) while for the other number the occurrences are fixed at n_2.

I've been looking around for and tried using seq and rep to do it but I can't seem to figure it out.

Here is an example for c(0,1) and n_1=5, n_2=3:

0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,0,0,1,1,1,0,1,1,1

And here for c(0,1) and n_1=2, n_2=1:

0,0,1,0,1
Cœur
  • 37,241
  • 25
  • 195
  • 267
Seb
  • 370
  • 2
  • 14

4 Answers4

10

Maybe something like this?

rep(rep(c(0, 1), n_1), times = rbind(n_1:1, n_2))
##  [1] 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1

Here it is as a function (without any sanity checks):

myfun <- function(vec, n1, n2) rep(rep(vec, n1), times = rbind(n1:1, n2))

myfun(c(0, 1), 2, 1)
## [1] 0 0 1 0 1

inverse.rle

Another alternative is to use inverse.rle:

y <- list(lengths = rbind(n_1:1, n_2),
          values = rep(c(0, 1), n_1))
inverse.rle(y)
##  [1] 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
4

An alternative (albeit slower) method using a similar concept:

unlist(mapply(rep,c(0,1),times=rbind(n_1:1,n_2)))
###[1] 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1
Mike H.
  • 13,960
  • 2
  • 29
  • 39
3

Here is another approach using upper-triangle of a matrix:

f_rep <- function(num1, n_1, num2, n_2){
    m <- matrix(rep(c(num1, num2), times=c(n_1+1, n_2)), n_1+n_2+1, n_1+n_2+1, byrow = T)
    t(m)[lower.tri(m,diag=FALSE)][1:sum((n_1:1)+n_2)]
}

f_rep(0, 5, 1, 3)
#[1] 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1

f_rep(2, 4, 3, 3)
#[1] 2 2 2 2 3 3 3 2 2 2 3 3 3 2 2 3 3 3 2 3 3 3
989
  • 12,579
  • 5
  • 31
  • 53
1
myf = function(x, n){
    rep(rep(x,n[1]), unlist(lapply(0:(n[1]-1), function(i) n - c(i,0))))
}
myf(c(0,1), c(5,3))
#[1] 0 0 0 0 0 1 1 1 0 0 0 0 1 1 1 0 0 0 1 1 1 0 0 1 1 1 0 1 1 1
d.b
  • 32,245
  • 6
  • 36
  • 77