How to merge two lists in r to make a list of ranges?

I have lists in R as follows:

start <- c(1, 5, 11)
end <- c(2, 9, 13)

how do I concatenate them to make a list of non-contiguous ranges in this manner:

c(1:2, 5:9, 11:13)

>Solution :

Try Map

> Map(`:`, start, end)
[[1]]
[1] 1 2

[[2]]
[1] 5 6 7 8 9

[[3]]
[1] 11 12 13

or with unlist in addition

> unlist(Map(`:`, start, end))
 [1]  1  2  5  6  7  8  9 11 12 13

A more efficient way might be using sequence

> sequence(end - start + 1, start)
 [1]  1  2  5  6  7  8  9 11 12 13

Leave a Reply