Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create integer sequences defined by 'from' and 'to' vectors

I have two vectors which define start (from) indices and finish (to) indices:

Start = c(1, 10, 20)
Finish = c(9, 19, 30)

I want to create a list of all Start:Finish sequences along the two vectors, i.e. generate the sequences Start[1]:Finish[1] (1:9); Start[2]:Finish[2], and so on.

## [[1]]
## [1] 1 2 3 4 5 6 7 8 9
## 
## [[2]]
##  [1] 10 11 12 13 14 15 16 17 18 19
## 
## [[3]]
##  [1] 20 21 22 23 24 25 26 27 28 29 30

Preferably in some vectorized way. The values in 'Start' vector will always be larger than the corresponding elements in 'Finish' vector.

like image 686
John Waller Avatar asked Mar 19 '15 10:03

John Waller


2 Answers

Just use mapply:

Start = c(1,10,20)
Finish = c(9,19,30)
mapply(":", Start, Finish)
## [[1]]
## [1] 1 2 3 4 5 6 7 8 9
## 
## [[2]]
##  [1] 10 11 12 13 14 15 16 17 18 19
## 
## [[3]]
##  [1] 20 21 22 23 24 25 26 27 28 29 30
## 

You could, of course, also use Vectorize, but that's just a wrapper for mapply. However, Vectorize cannot be used with primitive functions, so you'll have to specify seq.default rather than seq, or seq.int.

Example:

Vectorize(seq.default)(Start, Finish)
## [[1]]
## [1] 1 2 3 4 5 6 7 8 9
## 
## [[2]]
##  [1] 10 11 12 13 14 15 16 17 18 19
## 
## [[3]]
##  [1] 20 21 22 23 24 25 26 27 28 29 30
## 
like image 92
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 23 '22 12:10

A5C1D2H2I1M1N2O1R2T1


Agree with @ColonelBeauvel and @nicola, though you could use seq instead of :, hence

Start = c(1, 10, 20)
Finish = c(9, 19, 30)
Map(seq, Start, Finish)
like image 38
JoeArtisan Avatar answered Oct 23 '22 13:10

JoeArtisan