rcost-optimization

How to cost minimize among markets


Hello there and thanks in advance. I have the current problem. I have a dataset that looks like this

data <- data.frame (id = 1:3, A = 1:3, B = 1:3)

Where:

My objective is to arrange a solution that shows up where is better to buy every id product.

Something like a data frame showing the best place to buy from every id item.

I have read some optimization packages info, so far i have no clue on how i can get this done. I think those packages might be for more complex tasks.


Solution

  • Your example isn't great, since A and B have the same value in each row; therefore neither A nor B is 'better' (i.e. lower). A more useful example is:

    data <- data.frame(id = 1:3, A = c(2, 4, 3), B = c(3, 5, 2))
    

    In which case you can do:

    library(dplyr)
    
    data %>%
      rowwise() %>%
      mutate(best = names(.)[which.min(c(A, B)) + 1])
    #> # A tibble: 3 x 4
    #> # Rowwise: 
    #>      id     A     B best 
    #>   <int> <dbl> <dbl> <chr>
    #> 1     1     2     3 A    
    #> 2     2     4     5 A    
    #> 3     3     3     2 B