Search code examples
rseqrep

R repeat a seqeunce reducing max value by 1


I have a sequence of days numbered from 0 (start) to say 5 (last day) I would like to create a list that repeats N times where N is number of days total, in this case it is 6 days (0,1,2,3,4,5), each consecutive repetition should reduce the length of the vector by 1.

So the output should be:

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

I have tried

for(i in 5:0){
i<-seq(from=0,to=i,by=1)
print(i)
}

This prints out the right output:

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

How can I write the output by each iteration to a vector? I tried assigning a listItems variable as 0 and use listItems[i] <- seq code but it only returns the last value in the for loop sequence which is 0.

I think I am missing something really bloody simple (as usual)


Solution

  • The most abstract way to do that is as follows:

    days <- 0:5
    days_decrement <- lapply(rev(seq_along(days)), head, x=days)
    days_decrement
    # [[1]]
    # [1] 0 1 2 3 4 5
    # 
    # [[2]]
    # [1] 0 1 2 3 4
    # 
    # [[3]]
    # [1] 0 1 2 3
    # 
    # [[4]]
    # [1] 0 1 2
    # 
    # [[5]]
    # [1] 0 1
    # 
    # [[6]]
    # [1] 0
    

    rev(seq_along(days) creates the vector of every iteration's last index and then lapply iterates over it with head to extract needed number of first elements. Iteration with number i can be accessed via days_decrement[[i]].

    This approach is general and can work with data frames and matrices when data is stored in rows (although rev(seq_along(days) should be changed to rev(seq_len(nrow(days)))).