6

我正在尝试习惯 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
4

3 回答 3

6

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

function(y, x, dataset, weights){
  f <- substitute(glm(y~x, data=dataset, weights=weights, family=binomial))
  logLik(eval(f))
}
于 2012-06-02T08:28:23.407 回答
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
于 2012-06-02T00:57:44.763 回答
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

于 2012-06-02T04:25:23.007 回答