0

我想使用glmMySQL 表中的数据计算适合 R 的模型的拟合值并将结果通过管道传回该表,我该怎么做?

4

1 回答 1

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')
于 2013-05-13T14:34:14.513 回答