optimize Function in R (Example) | One Dimensional Optimization
In this R tutorial you’ll learn how to perform a one dimensional optimization using the optimize() function.
The tutorial will contain these contents:
Let’s dig in…
Definition & Basic R Syntax of optimize Function
Definition: The optimize R function performs one dimensional optimization.
Basic R Syntax: You can find the basic R programming syntax of the optimize function below.
optimize(any_function, any_intervals) # Basic R syntax of optimize function |
optimize(any_function, any_intervals) # Basic R syntax of optimize function
In the following, I’ll show an example for the application of the optimize function in R programming.
Example: Optimizing User-Defined Function Using optimize() in R
The following R programming syntax illustrates how to use the optimize function in R. First, we have to create our own function that we want to optimize:
my_function <- function(x) { # Create function x^3 + 2 * x^2 - 10 * x } |
my_function <- function(x) { # Create function x^3 + 2 * x^2 - 10 * x }
Now, we can apply the optimize() command to optimize our user-defined function. In this example, we are using a lower interval limit of -1 and an upper interval limit of 1.
optimize(my_function, # Apply optimize interval = c(- 1, 1)) # $minimum # [1] 0.999959 # # $objective # [1] -6.999877 |
optimize(my_function, # Apply optimize interval = c(- 1, 1)) # $minimum # [1] 0.999959 # # $objective # [1] -6.999877
The RStudio console shows our final result: We found a minimum at the value 0.999959 and an objective (i.e. the location of the minimum).
Video & Further Resources
Would you like to learn more about one dimensional optimizations? Then you might have a look at the following video of my YouTube channel. I’m explaining the examples of the present article in the video.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Furthermore, you could read the related tutorials of this website:
To summarize: In this article you learned how to apply the optimize function in the R programming language. In case you have any further questions, let me know in the comments section below. Furthermore, don’t forget to subscribe to my email newsletter in order to receive updates on new articles.
Statistics Globe Newsletter