Skip to content
Prev 367137 / 398506 Next

evaluating function over seq of values

The reason you are having trouble with using an *apply function is
that f_like does
not have an argument 'N', so the N it uses is the N from the
environment in which
f_like was defined, .GlobalEnv, not one you might set in *apply's FUN argument.
Hence, make N an argument to f_like and use it in *apply.  I like
vapply since it gives
you error checking and predictable results.

f_like2 <- function(par, N) {
                            p1 <- par[1];
                            p2 <- par[2];
                            p3 <- par[3];
                            p4 <- par[4];
                                   lfactorial(N)-lfactorial(N-79) +
                                    (30*log(p1)+(N-30)*log(1-p1)) +
                                    (15*log(p2)+(N-15)*log(1-p2)) +
                                    (22*log(p3)+(N-22)*log(1-p3)) +
                                    (45*log(p4)+(N-45)*log(1-p4)) }
N <- seq(80, 200, 1)
like_mod <- vapply(N,
   FUN = function(Ni) {
      optim(c(0.2,0.2,0.2,0.2), function(par) f_like2(par, N=Ni),
         method = "L-BFGS-B", lower=c(0.005,0.005,0.005,0.005),
upper=c(0.990,0.995,0.995,0.995),
         hessian = TRUE,control=list(fnscale=-1))$value
      },
   FUN.VALUE=0.0)
plot(N, like_mod)
datNew <- cbind(count = seq_along(N), N = N, like_mod = like_mod) #
like your 'dat'

Bill Dunlap
TIBCO Software
wdunlap tibco.com
On Mon, Feb 13, 2017 at 8:41 AM, Evan Cooch <evan.cooch at gmail.com> wrote: