[R] Define return values of a function

David Winsemius dwinsemius at comcast.net
Sun Nov 22 14:44:14 CET 2009


On Nov 22, 2009, at 6:26 AM, soeren.vogel at eawag.ch wrote:

> I have created a function to do something:
>
> i <- factor(sample(c("A", "B", "C", NA), 793, rep=T, prob=c(8, 7, 5,  
> 1)))
> k <- factor(sample(c("X", "Y", "Z", NA), 793, rep=T, prob=c(12, 7,  
> 9, 1)))
> mytable <- function(x){
>  xtb <- x
>  btx <- x
>  # do more with x, not relevant here
>  cat("The table has been created, see here:\n")
>  print(xtb)
>  list(table=xtb, elbat=btx)
> }
> tbl <- table(i, k)
> mytable(tbl) # (1)
> z <- mytable(tbl) # (2)
> str(z) # (3)
>
> (1) Wanted: outputs the string and the table properly. *Unwanted*:  
> outputs the list elements.
>

Whet the author of a function wants a particular object that exists  
insode a function to be returned they may warp it in the function  
return(). Otherwise R returns the result of the last evaluation which  
in this case was list(table=xtb, elbat=btx).

If you want the function to return <something else>. then you could   
put <something else> last in the sequence. If you want it to return  
<nothing> than put this at the end:

return()

If you want the results to not be printed the use invisible()

Perhaps:
  invisible(list( elbat=btx))   #substituted for list(table=xtb,  
elbat=btx) after the print line

 > tbl <- table(i, k)
 > mytable(tbl) # (1)
The table has been created, see here:
    k
i     X   Y   Z
   A 119  69  89
   B 116  70  97
   C  80  36  52
 > z <- mytable(tbl) # (2)
The table has been created, see here:
    k
i     X   Y   Z
   A 119  69  89
   B 116  70  97
   C  80  36  52
 > str(z) # (3)
List of 1
  $ elbat: 'table' int [1:3, 1:3] 119 116 80 69 70 36 89 97 52
   ..- attr(*, "dimnames")=List of 2
   .. ..$ i: chr [1:3] "A" "B" "C"
   .. ..$ k: chr [1:3] "X" "Y" "Z"



> (2) and (3) Wanted: outputs the string properly. Wanted: assigns the  
> list properly.

If you want to return the list, elbat, then just put the name of the  
list last in your case inside invisible or put it inside return().


>
> How can I get rid of the *unwanted* part? That is, how do I define  
> what the functions prints

That set by cat and print in your case.

> and -- on the other hand -- what it returns without printing?

By return()  or the order of evaluation
>

--

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list