【发布时间】:2018-01-02 16:31:13
【问题描述】:
我正在使用 R 3.3.2。
我想根据往年的分数来预测各个子排名的机构分数。然后我需要将这些预测分数作为新行添加到原始数据框中。我的输入是一个 csv 文件
我想使用最小二乘线性模型,发现“lm”和“predict”完全符合我的需要。
我知道这是一个非常初学者的问题,但希望有人可以帮助我。请参阅下面的数据和代码以及我已经启动的两个解决方案。
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)
}
为了说明,这就是我想在最后得到的——黄色行是预测:
【问题讨论】:
标签: r loops dataframe append apply