Sequence all integers between two vectors in R

2019-01-04 03:30发布

I have two vectors:

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

I would like something like this to work...

Start:Finish

But of course it does not.

I would like to produce a list like 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 bigger than the Finish vector for a corresponding element.

2条回答
Luminary・发光体
2楼-- · 2019-01-04 04:13

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
## 
查看更多
看我几分像从前
3楼-- · 2019-01-04 04:32

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)
查看更多
登录 后发表回答