[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[1] * f(b[2] * x * f(b[3] * 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[[2]] <- substitute(f)
    ans <- quote(u*y)
    ans[[2]] <- b[length(b)]
    ans[[3]] <- namevec
    for (i in seq(length = length(b)-1)) {
        ans1 <- quote(u * y * f(v))
        ans1[[2]][[2]] <- b[i]
        ans1[[2]][[3]] <- name.var
        ans1[[3]][[1]] <- fun
        ans1[[3]][[2]] <- 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
Madison, WI 53706-1685
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list