Reputation: 7121
I have a multi-variable equation that I have concluded after some analysis. I would like to write this equation in the form of a glm in R. I am doing this so that I can use the "predict" and other functions on this equation. Would that be possible?
Here are the details of my equation
intercept:15.67
variable1 coefficient: -3.2
variable2 Coefficient -0.8
I know it sounds as simple task but I couldn't find a function to convert an equation into a glm (something like "as.glm"!) Is this possible?
Thanks
Upvotes: 0
Views: 1164
Reputation: 206232
I've had to do this in the past so i wrote a helper function to create a fake glm object called makeglm. There's actualyl a bunch of stuff you need to set up so you can use predict()
including specifying classes for columns. The function itself requests a data.frame from which it can infer data types. Here's an example of how you would use it.
#sample data
set.seed(15)
dd <- data.frame(
X1=runif(50),
X2=factor(sample(letters[1:4], 50, replace=T)),
X3=rpois(50, 5),
Outcome = sample(0:1, 50, replace=T)
)
# fit standard model
mymodel<-glm(Outcome~X1+X2+X3, data=dd, family=binomial)
predict(mymodel, type="response")
#create a "fake" model and still use predict
newmodel <- makeglm(Outcome~X1+X2+X3, family=binomial, data=dd,
-.5, X1=1, X2=c(b=1.5, c=1, d=1.5), X3=-.15)
predict(newmodel, newdata=dd, type="response")
Upvotes: 1
Reputation: 94192
Here's a quick hack of a class of linear functions. I'm fairly sure something better must exist somewhere... But anyway:
linear <- function(betas){
betas = matrix(betas, ncol=1)
ret = list(
pred = function(z){
(cbind(1,z) %*% betas)[,1]
}
)
class(ret)="linear"
ret
}
predict.linear <- function(object, newdata, ...){
object$pred(newdata)
}
Then you can do:
> l1 = linear(c(15,1,2))
> predict(l1,cbind(1:10,12:21))
[1] 40 43 46 49 52 55 58 61 64 67
Which is just:
> 15 + 1*(1:10) + 2*(12:21)
[1] 40 43 46 49 52 55 58 61 64 67
ie intercept plus explanatory variables * coefficients.
Note this relies on the order of the columns in the matrix, rather than the names of variables in a data frame. As I said, there's probably a better, more usable implementation out there so I don't want to develop this much further. Have a print method:
print.linear <- function(x,...){
cat("Linear interpolator\n")
cat("Parameters: ",x$betas)
cat("\n")
invisible(0)
}
So it now says:
> l1
Linear interpolator
Parameters: 15 1 2
when you print it.
If you really want generalised linear models then you'll have to specify a family (Poisson, Binomial etc) and a link function in there somewhere.
Upvotes: 2