Sequence of two numbers with decreasing occurrence of one of them
Asked Answered
D

4

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
Dimeter answered 17/3, 2017 at 13:13 Comment(0)
N
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
Narco answered 17/3, 2017 at 13:19 Comment(1)
times = rbind(n_1:1, n_2) without c() should sufficeGriego
S
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
Saint answered 17/3, 2017 at 13:35 Comment(0)
K
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
Kaffraria answered 17/3, 2017 at 13:58 Comment(0)
I
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
Incommutable answered 17/3, 2017 at 14:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.