Search code examples
rforecastingrbind

Add Row with Month Forecast / Run Rate


I have a dataframe as follows:

Date <- c('2017-01-01','2017-01-02','2017-01-03')
TypeA <- c(44, 45, 70)
TypeB <- c(67, 23, 45)
TOTAL <- c(111, 68, 115)
df<-data.frame(Date,TypeA, TypeB, TOTAL)

Date <- c('Total:')
TypeA <- c(159)
TypeB <- c(135)
TOTAL <- c(294)
df1<-data.frame(Date,TypeA, TypeB, TOTAL)

test11<-rbind(df,df1)

#         Date TypeA TypeB TOTAL
# 1 2017-01-01    44    67   111
# 2 2017-01-02    45    23    68
# 3 2017-01-03    70    45   115
# 4     Total:   159   135   294

How do I add a new row under the dataframe that shows the forecast for the month for each column? The formula I plan on using for TypeA for example is: 159/3*31 which is the (Total MTD/Length -1 of dataframe)*Days of Month.

I want the final output to look like this:

        Date TypeA TypeB TOTAL
1 2017-01-01    44    67   111
2 2017-01-02    45    23    68
3 2017-01-03    70    45   115
4     Total:   159   135   294
5  Run Rate:  1643  1395  3038 

Any help would be great, thanks!


Solution

  • levels(test11$Date) <- c(levels(test11$Date), 'Run Rate')
    runRate <- c(Date = "Run Rate", 
                 test11[nrow(test11), 2:ncol(test11)]/(nrow(test11)-1)*31
                 )
    test11 <- rbind(test11, runRate)
    

    I had to add "Run Rate" as another factor.