I have this kind of data:
df <- data.frame(year=c(1999,1999,1999,2000,2000,2001,2011,2011,2011,2011), class=c("A","B","C","A","C","A","B","C","D","E"),
n=c(10,20,30,12,15,40,50,55,60,5), occurs=c(0,1,3,4,2,0,0,11,12,2))
> df
year class n occurs
1 1999 A 10 0
2 1999 B 20 1
3 1999 C 30 3
4 2000 A 12 4
5 2000 C 15 2
6 2001 A 40 0
7 2011 B 50 0
8 2011 C 55 11
9 2011 D 60 12
10 2011 E 5 2
I would like to expand this data like this:
year class n occurs
1 1999 A 1 0
1 1999 A 2 0
1 1999 A 3 0
...
1 1999 A 10 0
2 1999 B 0 0
2 1999 B 1 0
2 1999 B 2 0
...
2 1999 B 20 1
3 1999 C 1 1
3 1999 C 1 1
3 1999 C 1 0
3 1999 C 1 0
.. the rest of occurs is seq of zeros...because `n-occurs` = 27 zeros and seq of 3x `1`.
I want to expand the rows n
times as indicated by column n
and so that the occurs
column expands to flag 0
or 1
n-times according to the number of occurs
columns number so if column occurs
has interger 5
and column n = 10
then there will be n
rows (year and class the same) and flags occurs
5 times zero
and 5 times number one
.
EDIT: Please note the new sequence of occurs
(seq only of 0
and 1
) is based on n-occurs
for number of 0
s and number of 1
is determined by number occurs
.