nest: Apply a function recursively

Description Usage Arguments Value Examples

View source: R/nest.R

Description

Implementation of the Nest function from the Wolfram language. Syntax order has been changed so that the function is compatible with the pipe operator (see %>%).

Usage

1
nest(x, expr, n, m = 1, xname = "x")

Arguments

x

an object or a variable name.

expr

an expression or a function to be evaluated recursively.

n

number of iterations.

m

return results of the last m iterations. Setting m = "all" returns a list of all results. This is equivalent to NestList function from the Wolfram language.

xname

character string containing the name of the argument that will be used recursively.

Value

a list or a vector of length m containing the results or a function; list of functions will be returned if m > 1.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
## Some of these examples are directly taken from the Wolfram documentation

## Newton iterations for \sqrt{2}
nest(1, (x + 2/x)/2, 5)

## Last two terms of the Fibonacci sequence
nest(c(1, 1), c(x[2], x[1] + x[2]), 10, m = "all")

## Gray codes of length 4
nest(0, c(x, length(x) + rev(x)), 4)

## Multi-log transformation
multi_log <- nest(x, log(x + 1), 4)

## Changing xname can imitate the use of '#' in the Wolfram language
## Both codes return a function. How are they different?
f1 <- nest(x, x^y, 4, xname = "y")
f2 <- nest(x, y^x, 4, xname = "y")

parksw3/wolframR documentation built on May 24, 2019, 6:16 p.m.