[R] A bug report?

Ernst Hansen erhansen at math.ku.dk
Thu Apr 15 08:35:56 CEST 2004


Ajay Shah writes:
 > buoyancy <- function(year, taxbase, tax, description, plotname) {
 >   cat("Simple full OLS regression with all data:\n")
 >   logtax = log(tax)
 >   logtaxbase = log(taxbase)
 >   m = lm(logtax ~ logtaxbase)
 >   summary.lm(m)
 >   details = summary.lm(m)
 > }

 > This program does not work. The summary.lm(m) statement seems to have
 > no effect. When I run it, I get:
 > 
 > $ R --slave < bugreport.R 
 > Simple full OLS regression with all data:
 > 
 > where it is asif the summary.lm(m) statement never occurred. If I put
 > in a statement print(m) it works, but the summary.lm(m) does not work.
 > 

Ajay, 

the short answer is: the summary.lm() step is carried out all right,
you just never get to see the result, because it is not written to the
console.  If you want it, just wrap it in an explicit print() call.

This is completely standard behaviour.  If you have

  myf <- function() {2; 10}

the call myf() will return the value 10, but the value 2 will not
be seen anywhere.  While

  myg <- function() {print(2); 10}

will write both the value 2 and the value 10 to the console. 


The reason you get a useful response from your function if you delete
the 'detail =...' line, is because it makes the call to summary.lm()
the last line of the function and hence returns it.  Effectively
making summary.lm() correspond to 10 in the above toy functions,
instead of corresponding to 2.  



There is a more tricky answer to your questions: As you have written
the function, it actually returns the results from the summary.lm()
call -  but it is deliberatly not printed!  

What the function returns, is the value of the last statement, which
happens to be an assignment.  The value of an assignement is the value
that is being assigned.  But the default printing behaviour of an
assignement is to be silent.  If you write

  x <- 1

at the prompt, seemingly nothing is returned...  But actually the
expression has the value 1, it is just not written anywhere.  If you write

  (x <- 1)

or

  print(x <- 1)

you will actually get the number 1 on the console.  


This suggests three alternative ways of curing your function: 

 1) add a final line

      details

 to the function, making it return the value of 'details' rather than
 the value of the assignement. 

 2) Put a set of parenthesis around the assignment, as in

     (details = summary.lm(m))
  

 3) Leave the function as it is, but print it explicitly.  That is, do
 not call it as

     buoyancy(...)
 
 but as

     print(buoyancy(...))



I hope this helps,


Ernst Hansen
Department of Statistics
University of Copenhagen




More information about the R-help mailing list