Generate a sequence with alternating increments in R?

I want to use R to create a sequence of numbers 1: 8, 11:18, 21:28, etc. up to 1000 (or the closest she can get, that is 998). Obviously, typing all this would be tedious, but since the sequence increases by one time and then jumps by 3, I'm not sure which function I could use to achieve this.

I tried seq(1, 998, c(1,1,1,1,1,1,1,3)) , but it does not give me the results that I am looking for, so I have to do something wrong.

+5
source share
4 answers

This is an ideal case of vectorization (reuse) in R. read about them

 (1:100)[rep(c(TRUE,FALSE), c(8,2))] # [1] 1 2 3 4 5 6 7 8 11 12 13 14 15 16 17 18 21 22 23 24 25 26 27 28 31 32 #[27] 33 34 35 36 37 38 41 42 43 44 45 46 47 48 51 52 53 54 55 56 57 58 61 62 63 64 #[53] 65 66 67 68 71 72 73 74 75 76 77 78 81 82 83 84 85 86 87 88 91 92 93 94 95 96 #[79] 97 98 
+6
source
 rep(seq(0,990,by=10), each=8) + seq(1,8) 
+5
source

You want to exclude the numbers 0 or 9 (mod 10) . Therefore, you can also try:

 n <- 1000 # upper bound x <- 1:n x <- x[! (x %% 10) %in% c(0,9)] # filter out (0, 9) mod (10) head(x,80) # [1] 1 2 3 4 5 6 7 8 11 12 13 14 15 16 17 18 21 22 23 24 25 26 27 # 28 31 32 33 34 35 36 37 38 41 42 43 44 45 46 47 48 51 52 53 54 55 56 57 # 58 61 62 63 64 65 66 67 68 71 72 73 74 75 76 77 78 81 82 83 84 85 # 86 87 88 91 92 93 94 95 96 97 98 

Or on a single line using Filter :

 Filter(function(x) !((x %% 10) %in% c(0,9)), 1:100) # [1] 1 2 3 4 5 6 7 8 11 12 13 14 15 16 17 18 21 22 23 24 25 26 27 28 31 32 33 34 35 36 37 38 41 42 43 44 45 46 47 48 51 52 53 54 55 56 57 # [48] 58 61 62 63 64 65 66 67 68 71 72 73 74 75 76 77 78 81 82 83 84 85 86 87 88 91 92 93 94 95 96 97 98 
+3
source

With a loop: for(value in c(seq(1,991,10))){vector <- c(vector,seq(value,value+7))}

-1
source

Source: https://habr.com/ru/post/1263296/


All Articles