Q:

Backfill data frame in R based on maximum number

I have a data frame with a number of id's and max values.
df <- data.frame(id = c("a", "b", "c"), max.number = c(0, 6, 4))

  id max.number
1  a          0
2  b          6
3  c          4

I want to create a new data frame that backfills down to zero for each id.  It would look like:
  id     number
1  a          0
2  b          0
3  b          1
4  b          2
5  b          3
6  b          4
7  b          5
8  b          6
9  b          0
10 c          1
11 c          2
12 c          3
13 c          4

I've tried to do this through a nested for loop but can't get it to work correctly.  I would love some guidance in doing this with apply if possible.

A:

This would be very easy with a data.table table:
# install.packages("data.table")
library(data.table)

df <- data.frame(id = c("a", "b", "c"), max.number = c(0, 6, 4))
dt <- as.data.table(df) 
# or directly: 
# dt <- data.table(id = c("a", "b", "c"), max.number = c(0, 6, 4))
dt[, .(number=seq(0, max.number)), by=id]

Output:
    id number
 1:  a      0
 2:  b      0
 3:  b      1
 4:  b      2
 5:  b      3
 6:  b      4
 7:  b      5
 8:  b      6
 9:  c      0
10:  c      1
11:  c      2
12:  c      3
13:  c      4

