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

322 Views Asked by At

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,...

6

There are 6 best solutions below

0
On

You may arrange the data in a matrix and extract 1st and 4th column.

val <- 1:100
sort(c(matrix(val, ncol = 4, byrow = TRUE)[, c(1, 4)]))

# [1]   1   4   5   8   9  12  13  16  17  20  21  24  25  28  29  32  33
#[18]  36  37  40  41  44  45  48  49  52  53  56  57  60  61  64  65  68
#[35]  69  72  73  76  77  80  81  84  85  88  89  92  93  96  97 100
0
On

A tidyverse option.

library(purrr)
library(dplyr)

map_int(1:11, ~ case_when(. == 1 ~ as.integer(1),
                          . %% 2 == 0 ~ as.integer(.*2),
                          T ~ as.integer((.*2)-1)))

#  [1]  1  4  5  8  9 12 13 16 17 20 21
0
On

We can try like below

> (v <- seq(21))[v %% 4 %in% c(0, 1)]
 [1]  1  4  5  8  9 12 13 16 17 20 21
1
On

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

0
On

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
0
On

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