`optim` a function including a caret prediction

Hi,

I'm trying to use optim with a prediction of a caret object. For example, trying to find the optimal number of cylinders, power and weight of a car in order to maximise miles per galon.

library("caret")
library("tidyverse")
data("mtcars")

# split
id <- 1:nrow(mtcars)
tr_rows <- sample(id, 22)
te_rows <- id[!id %in% tr_rows]

# features and outcome
features <- c("cyl", "hp", "wt")
outcome <- "mpg"

# data for ml
car_ml <- mtcars |> select(all_of(c(features, outcome)))

# regression
reg <- train(mpg ~ .,
      data = car_ml[tr_rows, ],
      method = "rf",
      verbose = FALSE
)

# minimization function
min_f <- function(x) {
  y <- predict(reg, newdata = x)
  return(-y)
}

# optimization
predict(reg, newdata = car_ml[1, ]) # works
optim(par = car_ml[1, ], fn = min_f) # Error in eval(predvars, data, env): object 'cyl' not found

I can't figure out why the cyl object is not found since it is present in the x data frame.

Thanks!

Although someone could come with a better explanation, I answer my own question. I don't know why, but I had to transpose x in the minimization function.

# minimization function
min_f <- function(x) {
  y <- predict(reg, newdata = t(x))
  return(-y)
}

🤷