3

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.

Jacob Myer
  • 479
  • 5
  • 22

2 Answers2

8

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
akrun
  • 874,273
  • 37
  • 540
  • 662
0

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
Maël
  • 45,206
  • 3
  • 29
  • 67