R: pass glm argument inside R function

I'm trying to get used to the issues of defining a region in R. I would like to call the glm() function inside the function, but it does not work, apparently for reasons that I could not fix with the assign() or eval() functions.

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 ao () function in 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's how to replicate my problem with the dataset I'm using

 library("MASS") data(menarche) mydata <- menarche mydata$Prop <- mydata$Menarche / mydata$Total 
+6
source share
3 answers

Replacement solution (@DWin suggestion).

 function(y, x, dataset, weights){ f <- substitute(glm(y~x, data=dataset, weights=weights, family=binomial)) logLik(eval(f)) } 
+5
source
 ao <- function (x, y, phi = seq (0,1,0.1), dataset, weights) { logLikvector <- rep(0,length(phi)) x <- dataset[,substitute(x)] y <- dataset[,substitute(y)] weights <- dataset[,substitute(weights)] 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 } return(logLikvector) } library("MASS") data(menarche) mydata <- menarche mydata$Prop <- mydata$Menarche / mydata$Total ao(y = "Prop",x = "Age", dataset = mydata, weights = "Total") [1] -55.37763 -55.37763 -55.37763 -55.37763 -55.37763 -55.37763 [7] -55.37763 -55.37763 -55.37763 -55.37763 -55.37763 
+2
source

I suggest creating a formula with paste and calling a function with do.call .

 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() f <- as.formula(paste(y, x, sep="~")) fit <- do.call("glm", list(formula=f, data=as.name(dataset), family="binomial", weights=as.name(weights))) logLikvector[i] <- logLik(fit) # get log likelihood } logLikvector } 

Then name it like this:

 ao("Prop", "Age", dataset="mydata", weights="Total") 

See fooobar.com/questions/661971 / ... for more details.

+1
source

Source: https://habr.com/ru/post/917227/


All Articles