[R] pass data to log-likelihood function
Duncan Murdoch
murdoch at stats.uwo.ca
Thu Sep 4 17:23:03 CEST 2008
On 9/4/2008 10:54 AM, Jinsong Zhao wrote:
> Hi there,
>
> When I do bootstrap on a maximum likelihood estimation, I try the
> following code, however, I get error:
>
> Error in minuslogl(alpha = 0, beta = 0) : object "x" not found
>
> It seems that mle() only get data from workspace, other than the
> boot.fun().
This is the way R does scoping. Your ll function was defined in the
global environment, so that's where it will look for x, n and r. If you
want it to look at the local variables in boot.fun, then you should
define it in boot.fun.
Duncan Murdoch
> My question is how to pass the data to mle() in my case.
>
> I really appreciated to any suggestions.
>
> Best wishes,
> Jinsong
>
> #-----------code start here---------------
> x <- c(32, 16, 8, 4, 2, 1)
> r <- c(20, 12, 10, 8, 6, 0)
> n <- c(20, 20, 20, 20, 20, 20)
>
> mydata <- data.frame(x = x, r = r, n = n)
> rm(x, r, n) #if not rmed, it will affect the final result.
>
>
> ll <- function(alpha, beta) { #how to pass the data to this function?
> x <- log10(x)
> P <- pnorm(alpha + beta * x)
> P <- pmax(pmin(P,1),0)
> -(sum(r * log(P)) + sum((n - r)* log(1-P)))
> }
>
> boot.fun <- function(data, index) {
> boot.data <- data[index, ]
> # it seems that the following three line dose nothing with the mle()
> x <- boot.data$x
> r <- boot.data$r
> n <- boot.data$n
> fit <- mle(ll, start = list(alpha = 0, beta = 0), method = "BFGS")
> boot.coef <- coef(fit)
> stats <- -boot.coef[1] / boot.coef[2]
> }
>
> library(stats4)
> library(boot)
>
> myboot <- boot(mydata, boot.fun, R = 199)
> # give the error message:
> # Error in minuslogl(alpha = 0, beta = 0) : object "x" not found
> #-----------code end here---------------
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list