Jacob Myer
Jacob Myer

Reputation: 509

R repeating sequence add 1 each repeat

I have a workbook problem for my R class I can't figure out. I need to "write an R command that uses rep() to create a vector with elements 1 2 3 4 2 3 4 5 3 4 5 6 4 5 6 7"

It seems to be a repeating sequence of 1 to 4, repeating 4 times and on each repeat adding 1 to the starting element. I'm very very new to R so I'm stumped. Any help would be appreciated.

Upvotes: 3

Views: 1849

Answers (2)

Maël
Maël

Reputation: 52399

Another option is to use sequence:

sequence(rep(4, 4), 1:4)
#[1] 1 2 3 4 2 3 4 5 3 4 5 6 4 5 6 7

Upvotes: 0

akrun
akrun

Reputation: 887951

We can use rep and add with the initial vector

v1 + rep(0:3, each = length(v1))
#[1] 1 2 3 4 2 3 4 5 3 4 5 6 4 5 6 7

Or using sapply

c(sapply(v1, `+`, 0:3))

Or using outer

c(outer(v1, 0:3, `+`))

data

v1 <- 1:4

Upvotes: 8

Related Questions