Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

R : Pass argument to glm inside an R function

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Solution with substitute (@DWin suggestion).

function(y, x, dataset, weights){
  f <- substitute(glm(y~x, data=dataset, weights=weights, family=binomial))
  logLik(eval(f))
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...