R:在R函数内将参数传递给glm

时间:2012-06-01 22:55:25

标签: r function glm

我正在尝试习惯R中的范围问题。我想在函数内部调用函数glm()但它不起作用,显然出于范围界限的原因我无法修复函数assign()eval()

这是一个简化版本:

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
}

现在我想在我的数据集上使用函数ao()

    ao (y = Prop, x = Age, dataset = mydata, weights = Total) 

这不起作用,但以下工作:

ao (y = mydata$Prop, x = mydata$Age, dataset = mydata, weights = mydata$Total)

有谁知道该怎么做?

任何帮助将不胜感激!!!

顺便说一下,以下是如何使用我正在使用的数据集复制我的问题

library("MASS")
data(menarche)
mydata <- menarche
mydata$Prop <- mydata$Menarche / mydata$Total

3 个答案:

答案 0 :(得分:6)

替代解决方案(@DWin建议)。

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

答案 1 :(得分:3)

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 :(得分:2)

我建议使用paste创建公式并使用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
}

然后这样称呼:

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

有关详细信息,请参阅https://stackoverflow.com/a/7668846/210673