The following recursively walks the expression tree.  The esub
function is from this page (you may wish to read that entire thread):
http://tolstoy.newcastle.edu.au/R/help/04/03/1245.html

esub <- function(expr, sublist) do.call("substitute", list(expr, sublist))

proc <- function(e, env = parent.frame()) {
   for(nm in all.vars(e)) {
      if (exists(nm, env) && is.language(g <- get(nm, env))) {
         if (is.expression(g)) g <- g[[1]]
            g <- Recall(g, env)
            L <- list(g)
            names(L) <- nm
             e <- esub(e, L)
          }
        }
     e
}

mat <- expression(0, f1*s1*g1)
g1 <- expression(1/Tm)
vals <- data.frame(f1=1, s1=.5, Tm=2)
e <- sapply(mat, proc)
sapply(e, eval, vals)

The last line should give:

> sapply(e, eval, vals)
[1] 0.00 0.25


On Fri, Jan 29, 2010 at 11:51 AM, Jennifer Young
<jennifer.yo...@math.mcmaster.ca> wrote:
> Hallo
>
> I'm having trouble figuring out how to evaluate an expression when one of
> the variables in the expression is defined separately as a sub expression.
> Here's a simplified example
>
> mat <- expression(0, f1*s1*g1)  # vector of formulae
> g1 <- expression(1/Tm)          # expansion of the definition of g1
> vals <- data.frame(f1=1, s1=.5, Tm=2) # one set of possible values for
> variables
>
> before adding this sub expression I was using the following to evaluate "mat"
>
> sapply(mat, eval, vals)
>
> Obviously I could manually substitute in 1/Tm for each g1 in the
> definition of "mat", but the actual expression vector is much longer, and
> the sub expression more complicated. Also, the subexpression is often
> adjusted for different scenarios.  Is there a simple way of changing this
> or redefining "mat" so that I can define "g1" like a macro to be used in
> the expression vector.
>
> Thanks!
> Jennifer
>
> ______________________________________________
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to