1

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.

Julián Urbano
  • 8,378
  • 1
  • 30
  • 52
  • 1
    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 02:10
  • 1
    [This answer of mine](http://stackoverflow.com/questions/10938427/example-needed-change-the-default-print-method-of-an-object/10938565#10938565), to a similar question, might help you get started with this. – Josh O'Brien May 10 '13 at 02: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 Answers1

0

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)
return(return.list)

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.

Tommy Levi
  • 771
  • 5
  • 12