Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequence of two numbers with decreasing occurrence of one of them

Tags:

r

sequence

seq

rep

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
like image 620
Seb Avatar asked Mar 17 '17 13:03

Seb


1 Answers

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
like image 109
A5C1D2H2I1M1N2O1R2T1 Avatar answered Sep 24 '22 05:09

A5C1D2H2I1M1N2O1R2T1