Home > Enterprise >  RShiny: Optimize Function to Equal Value
RShiny: Optimize Function to Equal Value

Time:01-12

I'm exploring optimization in RShiny and have produced the following example based on another example I found:

library(shiny)
#library(optimx)


fr <- function(x) {   
   x1 <- x[1]
   x2 <- x[2]
   2*(x[1]-1)^2   5*(x[2]-3)^2   3 
  # 100 * (x2 - x1 * x1)^2   (1 - x1)^2
  #x*x
}




ui <- fluidPage(
  titlePanel("Values"),
  
  sidebarLayout(
    sidebarPanel(
      sliderInput("range", 
                  label = "Choose two Values:",
                  min = -5, max = 5, value = c(-5, 5))
      
    ),
    mainPanel(
      textOutput("optim_out"),
      textOutput("optim_out_b")
    )
  )
)

# Define server logic required to draw a histogram
server <- function(input, output) {
  out <- reactive(optim(c(input$range[1], input$range[2]), fr))
  output$optim_out_b <- renderText(paste0("Par: ", out()$par[1], ", ", out()$par[2], " Value: ", out()$value, " Convergance: ", out()$convergence))
}

# Run the application 
shinyApp(ui = ui, server = server)

When the code is run, x1 turns out to be 1 and x2 is 3. My question is can I optimize the formula in function in a way that I can set the formula equal to a value, and then optimize. For example, is there a way to do:

2*(x[1]-1)^2   5*(x[2]-3)^2   3 = 172

And have the function optimized so that the values x1 and x2 are spit out with values that produce either 172 or the number closest to 172 as possible?

I tired just adding the = 172 to my function and it didn't work, that's just an example of what i'd like to do.

CodePudding user response:

  1. Even though you intend to use shiny the question itself has nothing to do with it and shiny should be left out of the question and should not be a tag to satisfy the requirement that questions be minimal. Also optimx is not used in the question but appears in a library statement.

  2. With two variables and one equation there won't be a unique solution but if you want any solution try minimizing the squared difference between fr and 172. Different starting values may produce different solutions.

Code--

optim(c(1, 1), function(x) (fr(x) - 172)^2)

giving:

$par
[1]  4.025171 -2.489776

$value
[1] 7.184557e-05

$counts
function gradient 
      49       NA 

$convergence
[1] 0

$message
NULL
  •  Tags:  
  • Related