R : Pass argument to glm inside an R function

前端 未结 3 1705
囚心锁ツ
囚心锁ツ 2020-11-30 15:24

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 di

相关标签:
3条回答
  • 2020-11-30 15:36
    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
    
    0 讨论(0)
  • 2020-11-30 15:42

    Solution with substitute (@DWin suggestion).

    function(y, x, dataset, weights){
      f <- substitute(glm(y~x, data=dataset, weights=weights, family=binomial))
      logLik(eval(f))
    }
    
    0 讨论(0)
  • 2020-11-30 15:59

    I suggest creating the formula with paste and calling the 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 call it like this:

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

    See https://stackoverflow.com/a/7668846/210673 for more details.

    0 讨论(0)
提交回复
热议问题