rsequencerepeatseqrep

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.


Solution

  • 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