Use rep() and seq() to create a vector

Viewed 468

I am new to R. In JAVA I would introduce a control variable to create a sequence such as

1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9

I was thinking on doing something like

seq(from=c(1:5),to=c(5,10),by=1)

However that does not work...

Can that be solved purely with seq and rep?

4 Answers

Try this. You can create a function to create the sequence and apply to an initial vector v1. Here the code:

#Data
v1 <- 1:5
#Code
v2 <- c(sapply(v1, function(x) seq(from=x,by=1,length.out = 5)))

Output:

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

And the way using seq() and rep() can be:

#Code2
rep(1:5, each = 5) + 0:4

Output:

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

How about this?

rep(0:4, each=5)+seq(from=1, to=5, by=1)


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

Using outer is pretty concise:

c(outer(1:5, 0:4, `+`))
#>  [1] 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9

Note, 0:4 is short for seq(from = 0, to = 4, by = 1)

A perfect use case for Map or mapply. I always prefer Map because it does not simplify the output by default.

Map(seq, from = 1:5, to = 5:9)
[[1]]
[1] 1 2 3 4 5

[[2]]
[1] 2 3 4 5 6

[[3]]
[1] 3 4 5 6 7

[[4]]
[1] 4 5 6 7 8

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

You can use unlist() to get it the way you want.

unlist(Map(seq, from = 1:5, to = 5:9))
 [1] 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9
Note that `by = 1`, the default. 
Related