jrokh
jrokh

Reputation: 81

Vectors in R, using the components in two vectors to create a new vector

So I have a vector the represents start times (trt.start) and end times (trt.end). Each of the start times represents one treatment (which takes 400 days) and the corresponding position in the vector trt.end represents the end.

trt.start = c(10000,10090,10180,10270, 10360) 
trt.end = c(trt.start + 400)

Is there a way to (with out hard coding it), to create a new vector that will represent the duration of each treatment? So it will result in:

c(10000:10400, 10090:10490, 10180:10580, 10270:10670, 10360:10760)

I would like to be able to do this without hard coding because the trt.start vector will change values.

Thank you!

Upvotes: 1

Views: 235

Answers (1)

akrun
akrun

Reputation: 887048

In R, we can use Map to get the sequence of corresponding vectors in a list and then unlist the list to create the single vector

v1 <- unlist(Map(`:`, trt.start, trt.end))
length(v1)
#[1] 2005

If we need as a string

v1 <- sprintf("%d:%d", trt.start, trt.end)
v1
#[1] "10000:10400" "10090:10490" "10180:10580" "10270:10670" "10360:10760"

or with paste

v1 <- paste0(trt.start, ":", trt.end)
v1  
#[1] "10000:10400" "10090:10490" "10180:10580" "10270:10670" "10360:10760"

Or a vectorized option is to replicate the 'trt.start' and then add with sequence of values

v2 <- rep(trt.start, each = 401) + seq_len(401) -1
all.equal(v2, v1)
#[1] TRUE

Upvotes: 1

Related Questions