[R] Vector of Numbers Not Output to Screen

Bert Gunter gunter.berton at gene.com
Fri Jul 18 04:50:03 CEST 2014


Rolf et.al

I have not followed this thread closely and so have nothing to say
about whose or what explanation is correct.

However, the following statement is misleading, if not wrong:

---------------------------
foo <- function(){
x <- 17
x
y <- 42
y
}

If you type foo() you get

[1] 42

which is the *value returned by the function.  *****The value of the
"x" statement inside foo() is made invisible *****(and would have to
be enclosed by print() to be made visible).

-------------
The reason I consider the asterisked passage misleading is that this
is a matter of scope. "made invisible" implies some sort of
legerdemain.  The "x" defined within the function only exists within
the function environment and the binding of the symbol "x" to the
value there disappears when the function returns (as you well know).

ergo:

> x <- 1
>
> foo<- function() {
+   x <- 2
+   x
+ }
>
> foo()
[1] 2
> x
[1] 1

Also, in general, printing from within a function is a side effect and
is generally discouraged in functional style program in favor of
explicitly returning the results. However, this is honored as much in
the breach as the observance as, for example, that;s the way most of
traditional R graphics works.

Anyway, the horse is now well and truly dead, I think.

Cheers,
Bert

Bert Gunter
Genentech Nonclinical Biostatistics
(650) 467-7374

"Data is not information. Information is not knowledge. And knowledge
is certainly not wisdom."
Clifford Stoll




On Thu, Jul 17, 2014 at 6:48 PM, Rolf Turner <r.turner at auckland.ac.nz> wrote:
> On 18/07/14 11:32, David Winsemius wrote:
>>
>>
>> On Jul 17, 2014, at 9:27 AM, Rui Barradas wrote:
>>
>>> Hello,
>>>
>>> Also, unlike what the op says, if statements are functions, explaining
>>> the behavior he got.
>>
>>
>> I'm not sure that is correct. The help page says if() is a
>> control-construct. I think the function is actually "{"
>>
>>> {rnorm(10); rpois(10, 3)}
>>
>>   [1] 5 3 5 5 7 3 4 4 0 5
>>
>> See
>>
>> ?Paren
>
>
> It has nothing to do either with if() or Paren.  It is the ***user's***
> function that is suppressing the output.  Consider:
>
> foo <- function(){
> x <- 17
> x
> y <- 42
> y
> }
>
> If you type foo() you get
>
> [1] 42
>
> which is the *value returned by the function.  The value of the "x"
> statement inside foo() is made invisible (and would have to be enclosed by
> print() to be made visible).
>
> cheers,
>
> Rolf
>
>
> --
> Rolf Turner
> Technical Editor ANZJS
>
> ______________________________________________
> 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.



More information about the R-help mailing list