We frequently score data in database directly for simple models like linear or logisitc regression. It is always a little bit tricky to transfer all coefficients from R to SQL correctly. I thought I can make some R to SQL translation for glm result. For numeric variables this is pretty straightforward:
library(rpart)
fit <- glm(Kyphosis ~ ., data = kyphosis, family = binomial())
coefs <- fit$coef[2:length(fit$coef)]
expr <- paste0('1/(1 + exp(-(',fit$coef[1], '+', paste0('(',
coefs, '*', names(coefs), ')', collapse = '+'),')))')
print(expr)
a <- with(kyphosis, eval(parse(text = expr)))
b <- predict(fit, kyphosis, type = 'response')
names(b) <- NULL
all.equal(a, b)
The generated expr
is: 1/(1 + exp(-(-2.03693352129613+(0.0109304821420485*Age)+(0.410601186932733*Number)+(-0.206510049753697*Start))))
.
Is there a way how to make this work for factor
variables? I would like to put factors in case ... when ... then ... end
clause. Suppose we have the following model:
kyphosis$factor_variable <- rep(LETTERS[1:5],20)[1:81]
fit <- glm(Kyphosis ~ ., data = kyphosis, family = binomial())
I am browsing through structure of fit
, but do not see anything useful. Is the only option to parse names(fit$coef)
?
case when X = 'Y' then 1 else 0 end as factor_variableY