[Rd] Very Long Expressions
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Mon Jan 24 11:36:23 CET 2005
"McGehee, Robert" <Robert.McGehee at geodecapital.com> writes:
> Greetings,
> I'm having some difficulties with evaluating very long expressions
> (Windows/Linux 2.0.1), as seen below, and would greatly appreciate any
> help, thoughts or work arounds. Let's say that I wanted to see what I
> would get if I added 1 to itself 498 times. One way of doing this would
> be to evaluate the expression 1+1+1+...
>
> > eval(parse(text = paste(rep(1, 498), collapse = "+")))
> [1] 498
>
> However, if we try this with 499+ items we get no answer:
> > a <- eval(parse(text = paste(rep(1, 499), collapse = "+")))
> > a
> Error: Object "a" not found
>
> And if this eval is passed to any other function, that function exits
> without error and without returning and object.
>
> So it seems that we've reached some upper limit of evaluation terms.
> While the parser is able to correctly create the long expression, eval
> does not successfully evaluate it.
> My problem is that since the evaluator does not return an object, error,
> or warning, I'm not able to easily code around this problem. Also, I've
> thought of no easy way to "count" the terms in the expression to see
> whether we've breached the upper limit or not.
It's a bug. 1.9.1 had
> eval(parse(text = paste(rep(1, 499), collapse = "+")))
Error in eval(expr, envir, enclos) : evaluation nested too deeply:
infinite recursion / options(expression=)?
which also contains the hint about how to raise the limit.
You do see it if you do
> a <- try(eval(parse(text = paste(rep(1, 499), collapse = "+"))))
> a
[1] "evaluation nested too deeply: infinite recursion / options(expression=)?"
attr(,"class")
[1] "try-error"
but that's obviously no excuse for not printing the message. The
problem appears still to be present in r-devel (the version at hand
was dated Jan.12, though).
> If I were able to see if the eval would work on a particular expression,
> one thing I had considered was to make an eval.long wrapper that peels
> terms off the right hand side of an overly-long expression until every
> sub-expression is legal.
But do you *really* want to do it this way? Why?
BTW, it's not really the length of the expression but its depth. The
parse tree for 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 is really
(((((((1+2)+3)+4)+5)+6)+7)+8). So you get 7 levels of parentheses. You
can easily have less deeply nested parentheses:
((1+2)+(3+4))+((5+6)+(7+8))
With that sort of pattern, adding 500 terms requires a nesting no more
than 9 levels deep. Persuading R to nest that way is a bit tricky
though.
--
O__ ---- Peter Dalgaard Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics 2200 Cph. N
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-devel
mailing list