0

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)

user3674993
  • 129
  • 1
  • 9

4 Answers4

1

We can use the sequence

sequence(6:1)-1
#[1] 0 1 2 3 4 5 0 1 2 3 4 0 1 2 3 0 1 2 0 1 0
akrun
  • 874,273
  • 37
  • 540
  • 662
1

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)))).

echasnovski
  • 1,161
  • 8
  • 13
  • All of the answers were very good, some additions to the answer from evgeniC helped me get an answer to another conundrum. – user3674993 Jan 13 '17 at 04:41
0

A vector can only have one element per entry, if you want to assign the vector to one entry, I would suggest to use a list.

One approach would look like this:

retList <- list()
for (i in 5:0) {
    res <- 0:i
    retList <- append(retList, list(res))
}
retList
# [[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

# or access a part 
retList[[2]]
# [1] 0 1 2 3 4

Does that give you what you want?

David
  • 9,216
  • 4
  • 45
  • 78
0

I think this will do the trick...

unlist(lapply(5:0, seq, from = 0))

In essence, this uses lapply() to pass each value of c(5,4,3,2,1,0) to the to parameter of seq(), while holding the from parameter constant at 0. The results are in a list, hence unlist().

Geoffrey Poole
  • 1,102
  • 8
  • 10