Mark Heckmann
2008-Dec-09 17:44 UTC
[R] no implicit call of the print function within loops?
Dear R-users, I wonder why some functions produce output when they are called (I suppose due to an implicit call of the print function) but within a loop they do not: attach(anscomce) exp <- parse(text= "lm(x1 ~ y1)") eval(exp) Here the print() function seems to be called implicitly. If I do the same within a for-loop, it is not. for (i in c(1)){ eval(exp) } I know that I have to wrap it into a print function so it would work. But why is that so? In the eval() help I don't find any clues. As this happens with other functions as well, I would like to understand the causes and thus avoid some future mistakes. TIA, Mark
The general rule is that when you type something at the command line and that something returns a value, if you do not tell it what to do with the value, and the value has not been made invisible, then the value is printed. If you do:> tmp <- eval(exp)You will not see the output printed since you tell it what to do with the return value from eval, but without the assignment, it is not told what to do and so does the print. This is not unique to the eval function, but true for anything that returns a visible value, compare:> 3 + 4 > x <- 3 + 4 > (x <- 3 + 4)The implicit print does not happen inside of loops, batch processing, inside of functions, and probably a few other places. Hope this helps, -- Gregory (Greg) L. Snow Ph.D. Statistical Data Center Intermountain Healthcare greg.snow at imail.org 801.408.8111> -----Original Message----- > From: r-help-bounces at r-project.org [mailto:r-help-bounces at r- > project.org] On Behalf Of Mark Heckmann > Sent: Tuesday, December 09, 2008 10:44 AM > To: r-help at r-project.org > Subject: [R] no implicit call of the print function within loops? > > Dear R-users, > > I wonder why some functions produce output when they are called (I > suppose > due to an implicit call of the print function) but within a loop they > do > not: > > attach(anscomce) > exp <- parse(text= "lm(x1 ~ y1)") > eval(exp) > > Here the print() function seems to be called implicitly. > If I do the same within a for-loop, it is not. > > for (i in c(1)){ > eval(exp) > } > > I know that I have to wrap it into a print function so it would work. > But why is that so? In the eval() help I don't find any clues. > As this happens with other functions as well, I would like to > understand the > causes and thus > avoid some future mistakes. > > TIA, > Mark > > ______________________________________________ > R-help at 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.