Take the 2-minute tour ×

I'm writing a set of R functions that will be up online, publicly available, so I'd like to do a clean job here...for the first time.

Basically there is a function f that receives a dataframe and computes five real-valued numbers, call them x1,x2,x3,x4 and x5. Then, one can call a set of other functions g1,g2,g3 that, based on those five numbers, compute some other things. So I'd like those 5 numbers to be integrated in a single object, so to speak. Maybe even let those g_i functions be part of that object, like a method, or link to the original data that generated them.

Right now the f function just returns a vector with named entries, but I'd like it to be clean, have it's own print function, etc.

What is the best way to do this? I'm thinking of something similar to the lm function and the model objects. Are those R objects? I've never done anything like this in R, so any pointer will be much appreciated.

share|improve this question
Check out ?list, for a more general way to return several objects. To have your own print function, you need to add a class (see ?class) to your return value, say, class(x) <- "myclass", and define a function print.myclass <- function(...) { do_something(...) }. –  Ferdinand.kraft May 10 '13 at 2:10
This answer of mine, to a similar question, might help you get started with this. –  Josh O'Brien May 10 '13 at 2:19
Oh, didn't know it was all done with lists. I thought you had to define S3/S4 classes and all that. Any pointer to printing tabulated data as in summary.lm? If you post as answer I'll accept –  Julián Urbano May 10 '13 at 11:10

1 Answer 1

Have you thought of your f function returning a list? You could set it up the return bit as

return.list <- list(x1=x1.val , x2=x2.val, x3=x3.val, x4=x4.val, x5=x5.val)

Then you can access the variables you want by calling return.list$x1 and so on. This also works for returning more complicated things like data frames, tables or lists of lists.

share|improve this answer
What's wrong with just the base print.list? You get a summary by $var = val –  Tommy Levi May 10 '13 at 11:27

Your Answer


