Create forecast for subsets of dataframe and append to original file

Viewed 244

I am using R 3.3.2.

I would like to predict scores of institutions for various subrankings based on their scores in previous years. Then I need to add these predicted scores as new rows to the original dataframe. My input is a csv file

I want to use the least squares linear model and found that "lm" and "predict" does exactly what I need.

I know this a pretty beginner question, but hope someone can help me. Please see below the data and code with two solutions I've started.

score<-c(63.6,  60.3,   60.4,   53.4,   46.5,   65.8,   45.8,   65.9,   
44.9,   60, 83.5,   81.7,   81.2,   78.8,   83.3,   79.4,   83.2,   77.3,   
79.4)

year<-c(2013,   2014,   2015,   2016,   2014,   2014,   2015,   2015,   
2016,   2016,   2011,   2012,   2013,   2014,   2014,   2015,   2015,   
2016,   2016)

institution<-c(1422,    1422,   1422,   1422,   1384,   1422,   1384,   
1422,   1384,   1422,   1384,   1384,   1384,   1422,   1384,   1422,   
1384,   1422,   1384)

subranking<-c('CMP',    'CMP',  'CMP',  'CMP',  'SSC',  'SSC',  'SSC',  
'SSC',  'SSC',  'SSC',  'ETC',  'ETC',  'ETC',  'ETC',  'ETC',  'ETC',  
'ETC',  'ETC',  'ETC')

d <- data.frame(score, year, institution,subranking)


#-----------SOLUTION 1 -------------------

p<- unique(d$institution)
for (i in (1:length(p))){
  x<- d$score[d$institution==p[i]]
  y<- d$year[d$institution==p[i]]
  model<- lm(x~y)
  result<-predict(model, data.frame(y = c(2017,2018,2019,2020)))
  z<- cbind(result,data.frame(y = c(2017,2018,2019,2020)))
  print(z)
}

##----------SOLUTION 2 -------------------

calculate_predicted_scores <- function(scores, years) {predicted_scores <-0
mod = lm(scores ~ years)
predicted_scores<-predict(mod, data.frame(years = c(2017,2018,2019,2020)))
return(predicted_scores)
}

To illustrate, this is what I want to get at the end - the yellow rows are the predictions:

enter image description here

1 Answers
Related