Chapter 13. Beyond Basic Numerics and Statistics

Introduction

This chapter presents a few advanced techniques such as those you might encounter in the first or second year of a graduate program in applied statistics.

Most of these recipes use functions available in the base distribution. Through add-on packages, R provides some of the world’s most advanced statistical techniques. This is because researchers in statistics now use R as their lingua franca, showcasing their newest work. Anyone looking for a cutting-edge statistical technique is urged to search CRAN and the Web for possible implementations.

13.1. Minimizing or Maximizing a Single-Parameter Function

Problem

Given a single-parameter function f, you want to find the point at which f reaches its minimum or maximum.

Solution

To minimize a single-parameter function, use optimize. Specify the function to be minimized and the bounds for its domain (x):

> optimize(f, lower=lowerBound, upper=upperBound)

If you instead want to maximize the function, specify maximum=TRUE:

> optimize(f, lower=lowerBound, upper=upperBound, maximum=TRUE)

Discussion

The optimize function can handle functions of one argument. It requires upper and lower bounds for x that delimit the region to be searched. The following example finds the minimum of a polynomial, 3x4 − 2x3 + 3x2 − 4x + 5:

> f <− function(x) 3*x^4 − 2*x^3 + 3*x^2 − 4*x + 5
> optimize(f, lower=-20, upper=20)
$minimum
[1] 0.5972778

$objective
[1] 3.636756

The returned value is a list with two elements: ...

Get R Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.