问题描述
model <- Create(parameter1 = list(model = "a","b"),parameter2 = list(distribution = "x","y"))
该函数的四个输入是字符,并且具有尽可能多的值:
parameter1: "a","b","c","d","e"
parameter2: "x","y","z","w","t","v"
我已经尝试了几次 optim
函数,但没有成功。
感谢任何帮助。
解决方法
在每组可能的输入值处评估函数并取最少的值。
# 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,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