I want to expand the data frame under some conditions. This is a bit like this question of expanding data frames inside a data frame , but not exactly the same.
I have a data frame:
df = data.frame(ID = c(3,3,3,3, 17,17,17, 74, 74, 210, 210, 210, 210), amount = c(101, 135, 101, 68, 196, 65 ,135, 76, 136, 15, 15, 15 ,15), week.number = c(4, 6, 8, 10, 2, 5, 7, 2, 6, 2, 3, 5, 6))
I want to expand the data frame for each identifier, given min and max week.number and having 0 in the quantity column for this extension. Min week.number is 1 and max week.number is 10. Expected results:
df1 <- data.frame(ID = c(rep(3,10), rep(17, 10), rep(74, 10), rep(210, 10)),
amount = c(0, 0, 0, 101, 0, 135, 0, 101, 0, 68, 0, 196,
0, 0, 65, 0, 135, 0, 0, 0, 0, 76, 0, 0, 0,
136, 0, 0, 0, 0, 0, 15, 15, 0, 15, 15, 0, 0,
0, 0))
(Actually, I have thousands of identifiers, and the week number is from 1 to 160).
Is there an easy and quick way to do this?
Thank!