使用optimize函数求极大似然图最大值时遇参数错误问题咨询
Fix: Error in f(arg, ...) : unused argument (arg) with
optimize() in R Hey there, that error is super straightforward to fix—let's break it down:
The core issue is that the optimize() function automatically passes a single argument (the current value it's evaluating in your interval) to your target function, but your fml() function doesn't accept any arguments at all.
Looking at your fml definition:
fml<-function(){ q1<- Nominal(z, a, c, x[1]) q2<- Nominal(z, a, c, x[2]) p3<- Nominal(z, a, c, x[3]) q4<- Nominal(z, a, c, x[4]) p1<- 1 - q1 p2<- 1 - q2 p4<- 1 - q4 p <- p1*p2*p3*p4 q <- 1-p # Looks like you're missing a return statement here too! }
Step-by-step fixes:
- Add a parameter to
fml: Sinceoptimize()is for single-variable optimization, it will pass the value it's testing to the first argument of your function. Let's name it something meaningful, liketheta(the parameter you're trying to maximize the likelihood for). - Update your function to use this parameter: Replace the value you want to optimize with
theta(I'm guessing one of the inputs toNominal()is your target parameter—adjust this to match your actual logic). - Return the likelihood value:
optimize()needs a numeric value to maximize/minimize, so make sure your function returnsq(orp, depending on which is your likelihood metric). - Check variable scope: Ensure
z,a,c, andxare available in the environment wherefmlruns (either global environment, or pass them as additional arguments if needed).
Here's the revised code example:
# Define the function with a parameter for the value to optimize fml <- function(theta){ # Replace x[1] with theta (adjust this to match your actual optimization target) q1 <- Nominal(z, a, c, theta) q2 <- Nominal(z, a, c, x[2]) p3 <- Nominal(z, a, c, x[3]) q4 <- Nominal(z, a, c, x[4]) p1 <- 1 - q1 p2 <- 1 - q2 p4 <- 1 - q4 p <- p1 * p2 * p3 * p4 q <- 1 - p return(q) # Return the value we want to maximize } # Now call optimize() without errors optimize(f = fml, interval = c(-10,10), maximum = TRUE)
Quick extra note:
If you're trying to optimize multiple parameters (not just one), optimize() won't work—you'll need to use optim() instead, which handles multi-variable optimization. Also, double-check that your Nominal() function is defined correctly and that all dependencies are accessible to fml.
内容的提问来源于stack exchange,提问作者Admovin
相关产品推荐
相关产品推荐

