R : Pass argument to glm inside an R function
function, glm, r
Solution
Solution with substitute (@DWin suggestion).
function(y, x, dataset, weights){
f <- substitute(glm(y~x, data=dataset, weights=weights, family=binomial))
logLik(eval(f))
}
Problem
I am trying to get used to scoping issues in R. I'd like to call the function `glm()` inside a function but it does not work, apparently for scoping reasons I did not manage to fix with the functions `assign()` or `eval()`. Here is a simplified version: ``` ao <- function (y, x, phi = seq (0,1,0.1), dataset, weights) { logLikvector <- rep(0,length(phi)) # vector of zeros to be replaced thereafter for (i in 1:length(phi)) { # loop to use glm() fit <- glm (y ~ x, data = dataset, family = binomial, weights = weights) logLikvector[i] <- logLik(fit) # get log likelihood } logLikvector } ``` Now I want to use the function ao() on my dataset ``` ao (y = Prop, x = Age, dataset = mydata, weights = Total) ``` This does not work, but the following works: ``` ao (y = mydata$Prop, x = mydata$Age, dataset = mydata, weights = mydata$Total) ``` Does anyone know what to do ? Any help would be greatly appreciated !!! Btw, here is how to replicate my problem with the dataset I am using ``` library("MASS") data(menarche) mydata <- menarche mydata$Prop <- mydata$Menarche / mydata$Total ```