Skip to content
Prev 243802 / 398506 Next

using ``<-'' in function argument

On Thu, 2 Dec 2010 23:34:02 -0500
David Winsemius <dwinsemius at comcast.net> wrote:

            
Sounds like a fair summary of what Erik said, but it is subtly wrong.
R has lazy evaluation of its arguments.  There is nothing that forces
the assignment to be evaluated and to pass the result into the
function.  On the contrary, the assignment takes place when the
function evaluates the argument.  For example:

R> rm(list=ls(all=TRUE))
R> ls()
character(0)
R> foo <- function(x, y){
+ if (x > 3) cat(y, "\n")
+ x}
R> foo(4, bar <- 5)
5 
[1] 4
R> ls()
[1] "bar" "foo"
R> bar
[1] 5
R> foo(2, fubar <- 6)
[1] 2
R> fubar
Error: object 'fubar' not found
R> ls()
[1] "bar" "foo"
On the contrary, the opposite is also very likely.  One of my favourite
idioms is:

	plot(fm <- lm(y~x, data=some.data))

to (1) fit a model, (2) assign the fitted model to an object and (3)
look immediately at diagnostic plots.

Students came to me and said that the code in the lab sheet didn't
work and they were getting strange error messages "about objects not
being found".  They reassured me that they had typed in exactly what
was on the lab sheet.  Of course, once I got to their computer and
looked at their screen, it was clear that they had typed:

	plot(fm = lm(y~x, data=some.data))

Cheers,

	Berwin

========================== Full address ============================
Berwin A Turlach                      Tel.: +61 (8) 6488 3338 (secr)
School of Maths and Stats (M019)            +61 (8) 6488 3383 (self)
The University of Western Australia   FAX : +61 (8) 6488 1028
35 Stirling Highway                   
Crawley WA 6009                e-mail: berwin at maths.uwa.edu.au
Australia                        http://www.maths.uwa.edu.au/~berwin