The sequence of all integers between two vectors in R

I have two vectors:

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

I would like something like this to work ...

Start Done

But of course it is not .

I would like to create a list similar to the following:

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

Preferably in some vectorized way. The Start vector will always be larger than the Finish vector for the corresponding element.

+8
source share
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 this is just a wrapper for mapply . However, Vectorize cannot be used with primitive functions, so you need to specify seq.default , not 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 ## 
+15
source

Agree with @ColonelBeauvel and @nicola, although you can use seq instead : therefore

 Start = c(1, 10, 20) Finish = c(9, 19, 30) Map(seq, Start, Finish) 
+4
source

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


All Articles