I have a function which I would like to optimize based on a vector of integers. Essentially, I'm trying to find the maximum value by changing the order of the inputs. See an example below. My data is much larger so I'm wondering if there is a package that would be better than just randomly changing the "vec" input until I've found the maximum value?
library(dplyr)
df<-data.frame(id=c(1:5),Revenue=sample(201:205))
#Start with random set of numbers to arrange dataframe
vec=c(1,2,5,3,4)
function_1<-function(vec){
df$new_col <- vec
df<-df%>%arrange(new_col)
df2 <-
df %>% mutate(nearest = transform(., close_prev = id[apply(`diag<-`(m <-
as.matrix(dist(id)), Inf) / upper.tri(m), 2, which.min)])) %>% as_tibble()
df2 <- as_tibble(df2$nearest)
df2 <-
##This is my penalty function which penalizes the revenue if any previous ##row id is less than 5 away from the row id.
df2 %>% ungroup() %>% mutate(Penalty = ifelse(row_number() == 1, 1, if_else(abs(id- close_prev) > 1, 1, .6))) %>%
mutate(Revenue_Penalized = Revenue * Penalty)
df3<<-df2
df2<- sum(df2$Revenue_Penalized)
print(df2)
}
function_1(df)
GenSA attempt
x=GenSA(vec,function_1,lower=c(1,1,1,1,1),upper=c(5,5,5,5,5),control=list(maxit=100))
the parameter metrics are not integers. Also, the output should use all inputs from "vec". I'm sure i'm doing something incorrect.
Think i found a solution! thanks.
ga(type='permutation',fitness=function_1,lower=1,upper=5, maxiter=5)
The following worked for my problem using the GA package.
ga(type='permutation',fitness=function_1,lower=1,upper=5)