Skip to content
Prev 201331 / 398506 Next

Define return values of a function

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,