How can I control the output of a function in R (similar to lm)

I create a user-defined function in R that takes several different variables as input and creates data.frame, a graph, and some summary statistics stored in a list. I would only like to print the final statistics when calling the function, but to have access to the plot and data.frame when explicitly calling.

I think what I want is similar to how lm() works, but I'm not sure how this happens.

When I print the object returned by lm , I only get a printout of $call and $coefficients :

 lm(mtcars$mpg ~ mtcars$cyl) Call: lm(formula = mtcars$mpg ~ mtcars$cyl) Coefficients: (Intercept) mtcars$cyl 37.885 -2.876 

But obviously much more is available behind the scenes in calling the lm function.

 lm(mtcars$mpg[1:3] ~ mtcars$cyl[1:3])$residuals 1 2 3 -1.280530e-15 1.280530e-15 8.365277e-31 > unclass(lm(mtcars$mpg[1:3] ~ mtcars$cyl[1:3]) Call: lm(formula = mtcars$mpg[1:3] ~ mtcars$cyl[1:3]) Coefficients: (Intercept) mtcars$cyl[1:3] 26.4 -0.9 > unclass(lm(mtcars$mpg[1:3] ~ mtcars$cyl[1:3])) $coefficients (Intercept) mtcars$cyl[1:3] 26.4 -0.9 $residuals 1 2 3 -1.280530e-15 1.280530e-15 8.365277e-31 $effects (Intercept) mtcars$cyl[1:3] -3.741230e+01 1.469694e+00 1.810943e-15 .... $call lm(formula = mtcars$mpg[1:3] ~ mtcars$cyl[1:3]) $model mtcars$mpg[1:3] mtcars$cyl[1:3] 1 21.0 6 2 21.0 6 3 22.8 4 

I looked at the code for lm, but I don’t really understand what is happening.

+5
source share
1 answer

The result of calling lm is an object with the class attribute set to lm. Objects of this class have their own printing method (which you can call explicitly if you want to use print.lm ). You can do something similar to yourself by simply setting the class attribute of the object returned by your function, and then create your own print method. Here is an example:

 my.func <- function(x, y, z){ library(ggplot2) df <- data.frame(x, y, z) p <- ggplot(df, aes(x, y)) + geom_point() ds <- sapply(df, summary) op <- list(data = df, plot = p, summary = ds) class(op) <- 'my_list' op } print.my_list <- function(m){ print(m$summary) } a <- my.func(1:5, 5:1, rnorm(5)) a print.default(a) 

Since list a has a class attribute set to my_list , after you create a print method for it, this method is used whenever you print a list with this class. You can see the whole object by explicitly calling print.default . There is a very good explanation of the classes in R: http://adv-r.had.co.nz/OO-essentials.html .

+8
source

All Articles