我想使用glm
在MySQL表中的数据上计算R中模型拟合的拟合值,并将结果反馈到该表中,我该怎么做?
答案 0 :(得分: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')