2

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)
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
jsimpsno
  • 448
  • 4
  • 19
  • Will `optimize()` work? – sashahafner Oct 09 '21 at 00:54
  • I don't believe so as I have discrete values, ie (1,2,3,4,5) as my input. – jsimpsno Oct 09 '21 at 01:54
  • In your definition of the function, you give vec as a parameter, but you call it with df as paramater .. ? If I undestand, you are looking for a fast way to find the vec which will give the maximum result when passed to function_1 .. that's it ? – MrSmithGoesToWashington Oct 11 '21 at 08:54
  • that is correct! – jsimpsno Oct 11 '21 at 13:00
  • A first advice is to optimize the function itself .. each time you have a performance issue, you should consider using data.table rather than dplyr .. for the optimised search of vec, there are so many ways .. for exemple, you can use GenSA, but look at [taskView](https://cran.r-project.org/web/views/Optimization.html) .. – MrSmithGoesToWashington Oct 11 '21 at 14:42
  • thank you for the recommendation. I attempeted to use the GenSA package but i'm getting duplicative and non integer values for the input, which would make the solution incorrect. I've updated my question to include what i tried. – jsimpsno Oct 11 '21 at 15:00

1 Answers1

1

The following worked for my problem using the GA package.

ga(type='permutation',fitness=function_1,lower=1,upper=5)
jsimpsno
  • 448
  • 4
  • 19