BrentL
BrentL

Reputation: 73

Using multiple ranges to create a vector in R

How can I create a vector in R using vector ranges. For example say I have two vectors that designate range limits. Say,

V1=c(1,10,20)

V2=c(3,12,21)

I would like to do something that would intuitively look like:

c(V1:V2)

[1] 1 2 3 10 11 12 20 21

{this is meant to be the vectorized equivalent of c(1:3,10:12,20:21)}

Upvotes: 0

Views: 1105

Answers (3)

Rich Scriven
Rich Scriven

Reputation: 99321

Here is an alternative with the data.table package. If we create a grouping variable we can run : by each group then grab the column at the end.

library(data.table)
data.table(id = seq_along(V1), V1, V2)[, V1:V2, by = id]$V1
# [1]  1  2  3 10 11 12 20 21

Upvotes: 4

Bulat
Bulat

Reputation: 6969

Here is how you can do this with data.table:

library(data.table)
dt <- data.table(V1, V2)
dt <- dt[rep(1:.N, V2-V1+1), i := .I, by = V1][,
         res := 0:(.N-1) + V1, by = i]

Upvotes: 2

akuiper
akuiper

Reputation: 214927

You can use the Map function.

unlist(Map(`:`, V1, V2))
[1]  1  2  3 10 11 12 20 21

Upvotes: 6

Related Questions