user3897
user3897

Reputation: 561

Add sequence to each element of a vector

I have a vector as indicated below

x <- c(1,32,60,86,115,142,171,198)

I would like to create a sequence as seq(x[i],x[i]+2,by=1) for each element of the vector. The resulting vector should be

1,2,3,32,33,34,60,61,62,86,87,88.....

I was wondering if there is a function similar to rep to do this? Appreciate your input on this.

Upvotes: 2

Views: 1406

Answers (2)

akrun
akrun

Reputation: 886938

We can use the vectorized rep

rep(x, each = 3) + 0:2
#[1]   1   2   3  32  33  34  60  61  62  86  87  88 115 116 117 142 143
#[18] 144 171 172 173 198 199 200

Upvotes: 8

Ronak Shah
Ronak Shah

Reputation: 388797

You can use saaply to loop over every element of x and generate a sequence of numbers and combine them with c

c(sapply(x, function(x) seq(x, x+2)))

# [1]   1   2   3  32  33  34  60  61  62  86  87  88 115 116 117 142 143 144 171 172 173 
#       198 199 200

Upvotes: 1

Related Questions