Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - create vector with sequence c(1,4,5,8,9,12,13,16),etc

We are looking to create a vector with the following sequence:

1,4,5,8,9,12,13,16,17,20,21,...

Start with 1, then skip 2 numbers, then add 2 numbers, then skip 2 numbers, etc., not going above 2000. We also need the inverse sequence 2,3,6,7,10,11,...

like image 333
Canovice Avatar asked Oct 08 '21 19:10

Canovice


People also ask

How do I create a vector of equally spaced values in R?

A very efficient way to create equally-spaced numeric vectors is to use the seq() function, which is short for sequence. To use the seq() function, you can specify the start value of the sequence in the from argument, the limit end value in the to argument, and the increment in the by argument.


3 Answers

We may use recyling vector to filter the sequence

(1:21)[c(TRUE, FALSE, FALSE, TRUE)]
 [1]  1  4  5  8  9 12 13 16 17 20 21
like image 182
akrun Avatar answered Oct 22 '22 23:10

akrun


Here's an approach using rep and cumsum. Effectively, "add up alternating increments of 1 (successive #s) and 3 (skip two)."

cumsum(rep(c(1,3), 500))

and

cumsum(rep(c(3,1), 500)) - 1
like image 33
Jon Spring Avatar answered Oct 22 '22 23:10

Jon Spring


Got this one myself - head(sort(c(seq(1, 2000, 4), seq(4, 2000, 4))), 20)

like image 20
Canovice Avatar answered Oct 23 '22 00:10

Canovice