I'm trying to figure out the five fastest-growing topics for each quarter. I have a dataframe (will call it df) in R with three columns - a quarter number (df$QNum), the topic (df$Topic) and the number of records of that topic that quarter (df$Total_Hits).
Here's an example of how my dataframe df looks:
Total_Hits Topic QNum
10 Technology 1
86 Video Conferencing 1
14 Video Conferencing 2
10 Technology 3
1 Video Conferencing 1
12 Technology 21
I want to create a new column in df, df$QonQGrowth that, for each record, calculates the growth of Hits on that Topic over the previous quarter. I don't mind how it looks for df$QNum=1 but for the third record in this example, it would calculate: (Total_Hits/(Total_Hits, where Topic="Video Conferencing" and QNum=1)-1)
I think it would look something like the following but can't quite figure it out:
df$QonQGrowth <- (df$Total_Hits / ([a lookup of Total_Hits for df$Topic and (df$Qnum-1)?]))-1
The data set is pretty large so it's possible that there won't be a record for every topic every quarter.
Similar questions here and here but they're not doing exactly what I need.
Edit: This question also seems like it might be useful, using ddply or aggregate.
Thanks so much in advance!