[R] using ``<-'' in function argument
Berwin A Turlach
berwin at maths.uwa.edu.au
Fri Dec 3 06:54:53 CET 2010
On Thu, 2 Dec 2010 23:34:02 -0500
David Winsemius <dwinsemius at comcast.net> wrote:
> [...] Erik is telling you that your use of ncol<-4 got evaluated to
> 4 and that the name of the resulting object was ignored, howevert the
> value of the operation was passed on to matrix which used positional
> matching since "=" was not used.
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"
> Usually the problem facing newbies is that they want to save
> keystrokes and so use "=" for assignment (also a potential pitfall
> although not as likely to mess you up as the choice to use the
> two-keystroke path for argument assignment).
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
More information about the R-help
mailing list