[R] Using str() in a function.

Duncan Murdoch murdoch.duncan at gmail.com
Fri Jul 15 20:06:57 CEST 2011


On 15/07/2011 1:44 PM, Bert Gunter wrote:
> Below.
> -- Bert
>
> On Fri, Jul 15, 2011 at 10:31 AM, andrewH<ahoerner at rprogress.org>  wrote:
> >  Thanks, everybody, this has been very edifying. One last question:
> >
> >  It seems that sometimes when a function returns something and you don't
> >  assign it, it prints to the console, and sometimes it doesn't. I'm not sure
> >  I understand which is which. My best current theory is that, if the function
> >  returns NULL, by itself and not as part of some larger object, it does not
> >  print it, but non-null values are printed. Is that correct?
>
> -- No.
> It depends on whether the function uses invisible() in the return,
> ?invisible
>
> If invisible() is not used and the value is not assigned, it's
> printed. Otherwise not.cf:
>
> f<- function()NULL
> g<- function()invisible(NULL)
>
> f() ## NULL is printed
> g() ## nothing printed
>
> z1<- f() ## nothing printed
> z2<- g() ## nothing printed
>
> z1 ## NULL
> z2 ##NULL
>

Right.  And what invisible() does is set a flag so that the console is 
told "don't print this".  You can see the flag if you use the 
withVisible() function.  For example, with Bert's definitions,

 > withVisible(f())
$value
NULL

$visible
[1] TRUE

 > withVisible(g())
$value
NULL

$visible
[1] FALSE

Duncan Murdoch



More information about the R-help mailing list