[R] Using str() in a function.

Bert Gunter gunter.berton at gene.com
Thu Jul 14 07:27:18 CEST 2011


Folks: To thrash the dead horse a little more ...


> So, what about this one:
> GG<-c(1:4)
> testX3 <- function(X) {summary(X); return(str(X))}
> testX3(GG)
>
> int [1:4] 1 2 3 4
>
> I thought this was ignoring the summary() because it evaluates the return()
> first.  If it does the return(str(X)) when it encounters it, (1) why doesn't
> it send the summary() to the console (I'm guessing that it is because its
> output is local to the function), and (2) why doesn't it return the NULL
> that str() returns to the console?

1) ?? The return value of summary is not assigned to anything in the
function. When in the GUI, typing summary...) automatically prints the
value of the expression, BUT NOT IN A FUNCTION of course! "Sending"
the summary to the console within a function is your idea, not R's
behavior, thank goodness.

2) The function does return NULL! Assign the result and you'll see, e.g.

z <- testX3(GG)
z  ## NULL. Printed because typed at the console.

The other stuff that is printed is printed from within the function
when str() is called, because str() itself has cat() statements that
do printing **while** the function is executing... although, I think
they're buffered until the function finishes IIRC. You could have
discovered this yourself by looking at the code for str(), except that
requires knowing how to find non-visible S3 methods, which is a puzzle
if you don't know the trick.

If the above explanation still doesn't do it for you, please don't ask
me for further help, as I give up.

Cheers,
Bert






>
> again, thanks.  --andrewH
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Using-str-in-a-function-tp3655785p3666616.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.
>



-- 
"Men by nature long to get on to the ultimate truths, and will often
be impatient with elementary studies or fight shy of them. If it were
possible to reach the ultimate truths without the elementary studies
usually prefixed to them, these would not be preparatory studies but
superfluous diversions."

-- Maimonides (1135-1204)

Bert Gunter
Genentech Nonclinical Biostatistics
467-7374



More information about the R-help mailing list