Skip to content
Back to formatted view

Raw Message

Message-ID: <B37C0A15B8FB3C468B5BC7EBC7DA14CC62F65734B1@LP-EXMBVS10.CO.IHC.COM>
Date: 2009-11-23T17:31:00Z
From: Greg Snow
Subject: Define return values of a function
In-Reply-To: <1191B6D4-850B-44BD-9AF5-636FAB5232D2@eawag.ch>

If you want to control what gets printed in the output of your function, then you need to get into creating classes and methods.  Choose a class to return from your function, and create a print method for that class, then when you run your function the output will cause the print method to be called if you don't store the object, but the entire object will be available if stored.  E.g.:

testfunc <- function(x) {
	out <- list( a=summary(x), b=quantile(x), c=range(x) )
	class(out) <- 'myclass'
	return(out)
}

print.myclass <- function(x) {
	cat('my output:\n')
	print(x$a)
	cat('\n\n')
	cat('Q1: ',x$b[2], '\n')
	return(invisible(x))
}

testfunc(rnorm(100))
tmp <- testfunc(rnorm(100))
tmp
str(tmp)

Hope this helps,

-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Soeren.Vogel at eawag.ch
> Sent: Sunday, November 22, 2009 4:27 AM
> To: r-help at r-project.org
> Subject: [R] Define return values of a function
> 
> 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.
> 
> (2) and (3) Wanted: outputs the string properly. Wanted: assigns the
> list properly.
> 
> How can I get rid of the *unwanted* part? That is, how do I define
> what the functions prints and -- on the other hand -- what it returns
> without printing?
> 
> Thanks
> 
> S?ren
> 
> --
> S?ren Vogel, Dipl.-Psych. (Univ.), PhD-Student, Eawag, Dept. SIAM
> http://www.eawag.ch, http://sozmod.eawag.ch
> 
> ______________________________________________
> 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.