I have some events I am trying to enumerate in my data based on the order in which the occur, but conditioned on another variable (in this case Date) is not missing. I’ve somewhat stuck. My problem is that I need to do it only using base-R.
Here is an working example:
df <-
structure(list(Date = c("Sep 02 2012", "Sep 10 2012", "Sep 22 2012",
"Sep 23 2012", "Sep 23 2012", "Sep 23 2012", "Sep 24 2012", "Sep 24 2012",
"Sep 24 2012", "Dec 01 2012", "Sep 09 2014", NA), Event = c("005",
"006", "002", "003", "004", "007", "008", "010", "011", "012",
"009", "001"), Type = c("IND", "IND", "CON", "OUT", "OUT", "IND",
"CMA", "ASH", "CON", "ASH", "CMA", "IND")), .Names = c("Date",
"Event", "Type"), class = "data.frame", row.names = c(13L, 14L,
10L, 11L, 12L, 15L, 16L, 18L, 19L, 20L, 17L, 9L))
Gives me this data frame,
df
Date Event Type
13 Sep 02 2012 005 IND
14 Sep 10 2012 006 IND
10 Sep 22 2012 002 CON
11 Sep 23 2012 003 OUT
12 Sep 23 2012 004 OUT
15 Sep 23 2012 007 IND
16 Sep 24 2012 008 CMA
18 Sep 24 2012 010 ASH
19 Sep 24 2012 011 CON
20 Dec 01 2012 012 ASH
17 Sep 09 2014 009 CMA
9 <NA> 001 IND
What I would like to get,
new.df
Date Event Type Num_Type
13 Sep 02 2012 005 IND 1
14 Sep 10 2012 006 IND 2
10 Sep 22 2012 002 CON 1
11 Sep 23 2012 003 OUT 1
12 Sep 23 2012 004 OUT 2
15 Sep 23 2012 007 IND 3
16 Sep 24 2012 008 CMA 1
18 Sep 24 2012 010 ASH 1
19 Sep 24 2012 011 CON 1
20 Dec 01 2012 012 ASH 2
17 Sep 09 2014 009 CMA 2
9 <NA> 001 IND NA
You can do this with
aveandcumsum: