I wondered about S3 classes in R, if there is an option to define a default output element and keep the remaining elements kind of hidden. As an example, lets say we have a toy function that calculates certain things and reports them back as a S3 class, like this:
toy <- function(x){
resA <- mean(x)
resB <- length(x)
output <- list(resA=resA, resB=resB, x=x)
class(output) <- "toy"
output
}
When we access the result now via
res <- toy(c(1:10))
res
we get the whole list as an output, as it would be expected. But if we define then also an S3 print method
`print.toy` <- function(x){
print(x$resA)
}
we can give a standard output for print that hides unnecessary information (in that case resB
and x
) and the user sees only resA
. But this could cause some confusion, when you want to apply further calculations on your object of class toy
, e.g.
res <- toy(c(1:10))
res
# Produces an error
res + 1
# Accesses the correct variable of class toy:
res$resA + 1
My question is now, is there a way to define the list item resA
to be the standard value of a S3 class that should be taken if no variable is specified, so that the res + 1
call will work as well?
Thanks for reading this.