In R, using binomial() and lapply to constrain predict() values between 0 and 1
Question
I have a GLM, family=binomial(link=logit) model that I apply within a predict() function, seen below. The predict values go beyond zero and 1, but I would like to keep them as probabilities. So I use the binomial()$inverse command that can be then be used in the apply function.
This worked just fine the first time I ran it, but after closing R down and starting again, I now get this error:
Error in get(as.character(FUN), mode = "function", envir = envir) :
object 'ilogit' of mode 'function' was not found"
I've been struggling with this for hours, as this code normally worked. Does anyone have an idea about what I am doing wrong? Is there a better way of doing this?
My code is below. I've also tried other variation but can't get it to work.
## predicted probabilities
pp <- predict(logit_model,
newdata=data,
type="link",
se.fit=T)
ilogit <- binomial()$inverse
yhat_prob <- lapply(pp,ilogit) #converts to probabilities
Solution
If you want the probabilities, you can have them directly with type="response"
, as explained in the documentation, ?pregict.glm
.
For the error message you get, you probably need binomial()$linkinv
.
> str( binomial() )
List of 12
$ family : chr "binomial"
$ link : chr "logit"
$ linkfun :function (mu)
$ linkinv :function (eta)
$ variance :function (mu)
...
The lack of error was probably due to some package you had loaded, which defined an ilogit
function.