-1

I have the following function that I want to find the minimum:

model <- Create(parameter1 = list(model = "a" , "b"),
                parameter2 = list(distribution = "x" , "y"))

The four inputs of this function are characters, and have as possible values:

parameter1: "a", "b", "c", "d", "e"
parameter2: "x", "y", "z", "w", "t", "v"

I've tried the optim function a few times without success.

Any help is appreciated.

moreirasd
  • 117
  • 5

1 Answers1

2

Evaluate the function at every possible set of input values and take the least.

# test function
Create <- function(parameter1, parameter2) {
  sum(match(unlist(parameter1), p1), match(unlist(parameter2), p2))
}
  
p1 <- c("a", "b", "c", "d", "e")
p2 <- c("x", "y", "z", "w", "t", "v")
g <- expand.grid(p1, p1, p2, p2, stringsAsFactors = FALSE)

obj <- function(x) Create(x[1:2], x[3:4])
ix <- which.min(apply(g, 1, obj))

g[ix, ]
##   Var1 Var2 Var3 Var4
## 1    a    a    x    x

obj(g[ix, ])
## [1] 4
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • @Grothendieck I think it worked! As there is a lot of possible combinations I will update you on whether it will run OK. I only had to add `g <- data.frame(lapply(g, as.character), stringsAsFactors=FALSE)` as this function only accept character arguments. Thanks! – moreirasd Jul 27 '21 at 18:20
  • I got this error message: _Error in which.min(future_apply(g, 1, obj)) : 'list' object cannot be coerced to type 'double'_ – moreirasd Jul 27 '21 at 19:40
  • I have modified the answer to add stringsAsFactors=FALSE as an argument to grid.expand although for the Create shown in the answer it is not actually needed but doesn't hurt either. The self contained reproducible code in the answer works but the application of it will be up to you since you haven't provided a complete reproducible test case. – G. Grothendieck Jul 27 '21 at 21:08