Search code examples
rsequenceseqrep

How can I create this special sequence?


I would like to create the following vector sequence.

0 1 0 0 2 0 0 0 3 0 0 0 0 4

My thought was to create 0 first with rep() but not sure how to add the 1:4.


Solution

  • You can use rep() to create a sequence that has n + 1 of each value:

    n <- 4
    myseq <- rep(seq_len(n), seq_len(n) + 1)
    # [1] 1 1 2 2 2 3 3 3 3 4 4 4 4 4
    

    Then you can use diff() to find the elements you want. You need to append a 1 to the end of the diff() output, since you always want the last value.

    c(diff(myseq), 1)
    # [1] 0 1 0 0 1 0 0 0 1 0 0 0 0 1
    

    Then you just need to multiply the original sequence with the diff() output.

    myseq <- myseq * c(diff(myseq), 1)
    myseq
    # [1] 0 1 0 0 2 0 0 0 3 0 0 0 0 4