Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replicate alternating vector values

Tags:

r

vector

I can't figure out how to produce a vector from 3 to 50 where the even numbers are replicated twice and the uneven numbers once, such that the vector would be

3, 4, 4, 5, 6, 6, 7, 8, 8, 9, ..., 50, 50
like image 431
Cardinal Avatar asked Feb 09 '17 20:02

Cardinal


2 Answers

rep() will do the trick.

x <- 3:50
rep(x, (x %% 2 == 0) + 1L)
#  [1]  3  4  4  5  6  6  7  8  8  9 10 10 11 12 12 13 14 14 15 16 16 17
# [23] 18 18 19 20 20 21 22 22 23 24 24 25 26 26 27 28 28 29 30 30 31 32
# [45] 32 33 34 34 35 36 36 37 38 38 39 40 40 41 42 42 43 44 44 45 46 46
# [67] 47 48 48 49 50 50

x %% 2 == 0 gives a logical vector indicating which elements of x are even. Since the integer values of TRUE and FALSE are 1 and 0 respectively, adding 1 to x %% 2 == 0 gives us the vector we need for our times argument in rep().

If we're playing golf, we can shorten it to rep(x, (!x %% 2) + 1L).

Note that this method will also be useful if our original vector is not sequential, and we still want the even values replicated.

v <- c(1, 2, 4, 3, 6)
rep(v, (!v %% 2) + 1L)
# [1] 1 2 2 4 4 3 6 6
like image 129
Rich Scriven Avatar answered Sep 29 '22 05:09

Rich Scriven


we can merge a vector of all the values and a vector of the even numbers together:

sort(c(3:50, 2:25*2))
like image 29
dww Avatar answered Sep 29 '22 07:09

dww