Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get 'summary' to work with custom class in R

Tags:

package

r

I'm wondering how I can get the summary(object) to work with a custom class in a package I'm creating. For example, if you run the following:

testfunction <- function(x) {
  x.squared <- x^2
  x.double <- 2*x
  x.triple <- 3*x

  result <- list(squared = x.squared, double = x.double, triple = x.triple)
  class(result) <- "customclass"
  result
}

x <- rnorm(100)
output <- testfunction(x)
summary(output)

you will see that the output is quite useless. I can't, however, seem to find how to control this output. If someone could direct me towards something I'd be grateful.

(I could, of course, make a custom summary function such as summary.Custom(object), but I'd prefer to have the regular summary method working directly.

like image 314
hejseb Avatar asked Sep 08 '13 13:09

hejseb


2 Answers

Write a function called summary.customclass with the same arguments as summary (see args(summary) for that).

What you are doing there is creating a method of summary for an S3 class. You might want to read up on S3 classes.

like image 71
Spacedman Avatar answered Sep 18 '22 00:09

Spacedman


There is no summary.list function. If you want to use the summary.default function, you need to use lapply or sapply:

> lapply(output, summary)
$squared
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
 0.000013  0.127500  0.474100  1.108000  1.385000 11.290000 

$double
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
-6.7190 -1.0480  0.4745  0.3197  1.8170  5.1870 

$triple
    Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
-10.0800  -1.5720   0.7117   0.4796   2.7260   7.7800 

Or:

> sapply(output, summary)
          squared  double   triple
Min.    1.347e-05 -6.7190 -10.0800
1st Qu. 1.275e-01 -1.0480  -1.5720
Median  4.741e-01  0.4745   0.7117
Mean    1.108e+00  0.3197   0.4796
3rd Qu. 1.385e+00  1.8170   2.7260
Max.    1.129e+01  5.1870   7.7800
like image 32
IRTFM Avatar answered Sep 22 '22 00:09

IRTFM