2013-05-13 48 views
0

我想计算一个适合R的模型的拟合值,使用glm对MySQL表中的数据进行处理,并将结果返回到该表中,我怎么能这样做?将R模型的拟合值插入到MySQL表中

+0

我想这可能是因为经常interessing PPL要么知道的MySQL _or_ [R – Hoffmann 2013-05-13 14:41:37

+0

你要保存的预测值?回归系数? – Dason 2013-05-13 14:57:10

+0

我想保存预测(拟合)的值 – Hoffmann 2013-05-13 14:58:13

回答

1

# preparation 
library("RMySQL") 
con <- dbConnect(MySQL(), user="####", pass="###", host="127.0.0.1", db="###") 
on.exit(dbDisconnect(con)) 

# fetching the data and calculating fit  
tab <- dbGetQuery(con,"SELECT ID, dep, indep1, indep2 FROM table WHERE !(ISNULL(ID) OR ISNULL(dep) OR ISNULL(indep1) OR ISNULL(indep2))") 
regression = glm(tab$dep ~ tab$indep1 + tab$indep2, gaussian) 

# preparing data for insertion 
insert <- data.frame(tab$ID, fitted.values(regression) 
colnames(insert) <- c('ID', 'dep') 

# table hassle (inserting data, combining with previous table, deleting old and fitresult renaming combined back to original name 
if (dbExistsTable(con, '_result') { 
    dbRemoveTable(con, '_result'); 
} 
dbWriteTable(con, '_result', insert) 
dbSendQuery(con, 'CREATE TABLE temporary SELECT table.*, _result.dep FROM table LEFT JOIN result USING (ID)') 
dbRemoveTable(con, 'table') 
dbRemoveTable(con, '_result') 
dbSendQuery(con, 'RENAME TABLE temporary TO table')