Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Generate a sequence of numbers

Tags:

I am trying to create sequences of number of 6 cases, but with 144 cases intervals.

Like this one for example

c(1:6, 144:149, 288:293)  1   2   3   4   5   6 144 145 146 147 148 149 288 289 290 291 292 293 

How could I generate automatically such a sequence with

seq  

or with another function ?

like image 328
giac Avatar asked Jun 29 '15 16:06

giac


People also ask

How do you repeat numbers in a sequence in R?

How do you Repeat a Sequence of Numbers in R? To repeat a sequence of numbers in R you can use the rep() function. For example, if you type rep(1:5, times=5) you will get a vector with the sequence 1 to 5 repeated 5 times.


2 Answers

I find the sequence function to be helpful in this case. If you had your data in a structure like this:

(info <- data.frame(start=c(1, 144, 288), len=c(6, 6, 6))) #   start len # 1     1   6 # 2   144   6 # 3   288   6 

then you could do this in one line with:

sequence(info$len) + rep(info$start-1, info$len) #  [1]   1   2   3   4   5   6 144 145 146 147 148 149 288 289 290 291 292 293 

Note that this solution works even if the sequences you're combining are different lengths.

like image 192
josliber Avatar answered Sep 27 '22 18:09

josliber


Here's one approach:

unlist(lapply(c(0L,(1:2)*144L-1L),`+`,seq_len(6))) # or... unlist(lapply(c(1L,(1:2)*144L),function(x)seq(x,x+5))) 

Here's a way I like a little better:

rep(c(0L,(1:2)*144L-1L),each=6) + seq_len(6) 

Generalizing...

rlen  <- 6L rgap  <- 144L rnum  <- 3L  starters <- c(0L,seq_len(rnum-1L)*rgap-1L)  rep(starters, each=rlen) + seq_len(rlen) # or... unlist(lapply(starters+1L,function(x)seq(x,x+rlen-1L))) 
like image 20
Frank Avatar answered Sep 27 '22 16:09

Frank