# [R] Folding ?

Saikat DebRoy saikat at stat.wisc.edu
Mon Sep 25 06:25:51 CEST 2000

```>>>>> "Yves" == Yves Gauvreau <cyg at sympatico.ca> writes:

> Hi,
> I need to write a function that would look something like this:

>  S <- function(b=betas){
>      expression(b * f(b * x * f(b * x * f(...b[n-1] * x * f(b[n] *
> x)))...)
> }

> Where n is the number of element in b.

> Further I need to be able to evaluate S at some x numerically of course and
> I need to use "deriv" and produce dS/dx such that I can evaluate it also at
> some x.

> I tried building the S expression manually to test the deriv (D) function,
> evaluate them both and everything work's fine.

> My trouble is automating the building of the expression S that is dependent
> on the length of b.

Try the following.

fold.fun <-
function(b, f, name.var = x)
{
if (length(b) == 0)
return(1)
name.var <- substitute(name.var)
if (is.character(name.var))
name.var <- as.name(name.var)
fun <- quote((f))
fun[] <- substitute(f)
ans <- quote(u*y)
ans[] <- b[length(b)]
ans[] <- namevec
for (i in seq(length = length(b)-1)) {
ans1 <- quote(u * y * f(v))
ans1[][] <- b[i]
ans1[][] <- name.var
ans1[][] <- fun
ans1[][] <- ans
ans <- ans1
}
ans
}

You use it as in -

> fold.fun(1:2, exp)
1 * x * (exp)(2 * x)
> fold.fun(1:2, exp, y)
1 * y * (exp)(2 * y)

Hope this helps.

Saikat
--
Department of Statistics                       Email: saikat at stat.wisc.edu
University of Wisconsin - Madison              Phone: (608) 263 5948
1210 West Dayton Street                        Fax:   (608) 262 0032