[R] print() required sometimes in interactive use of console

Duncan Murdoch murdoch.duncan at gmail.com
Wed Jan 26 21:40:59 CET 2011


On 26/01/2011 3:27 PM, Giles Crane wrote:
> Surprising behavior:
> Most R users are aware that print()
> must be used inside functions to gain
> output on the console.
>
> Apparently, print() is sometimes required
> when interactively using the console.
> For example, the followingmay be
> entered into the R console with different results.
>
> sample(1:8,8)      #prints a permutation of 1 to 8
>
> for(i in 1:5)           #does not
>       sample(1:8,8)

What you say is right, but I think your mental model of what is going on 
is wrong.  The rule for printing is simple:  the result of an expression 
entered at the console is automatically printed unless it is marked 
invisible.

The result of for() {} is marked invisible, so it doesn't print.

The result of x <- 1 is marked invisible, so it doesn't print.

Expressions in functions are not entered at the console, so they don't 
print.

You can explicitly mark something as invisible, and it won't print.  For 
example,

invisible(sample(1:8, 8))

won't print.  Though it doesn't use the R function invisible(), that's 
essentially what happens in a for loop:      it returns NULL, but marked 
invisible, so it doesn't print.  (I seem to recall that in older 
versions it would return the last value of the loop, but that was 
changed some time ago, or I'm thinking of some other language.)

There's a function called withVisible() that returns a value and its 
visibility; you can experiment with that to see what's going on.  For 
example,

 > withVisible(x <- 1)
$value
[1] 1

$visible
[1] FALSE

Duncan Murdoch



More information about the R-help mailing list