Home How to add a default behaviour to an S3 class
Reply: 0

How to add a default behaviour to an S3 class

Dominique Makowski
1#
Dominique Makowski Published in 2018-01-10 22:44:09Z

I have this small package in which I create the class "psychobject", which is basically a list, on which I've added different methods (such as print, summary etc.).

I create these classes by doing the following:

function_that_returns_a_psychobject <-  function(x){
  output <- list(value = x+1)

  class(output) <- c("psychobject", "list")
  return(output)
}

As such, the output respond to psychobject methods but can also be treated as a regular list.

However, what bothers me is that when I enter a psychobject in the console, nothing happens:

output <- function_that_returns_a_psychobject(x=3)
output # does nothing
print(output) # does something

How can I add a default behaviour to this class, so that when just entering a psychobject in the console, in prints it?

I've tried creating a function based on my class as follows:

#' Creates or tests for objects of mode "psychobject".
#'
#' @param x an arbitrary R object.
#'
#' @export
psychobject <- function(x)
{
  print("Do something")
  UseMethod("psychobject", x)
}

But it doesn't seem to work :(


Reproducible example:

install.packages("psycho")
library("psycho")

results <- psycho::correlation(attitude)
print(results)  # Prints something
results  # Prints nothing
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.300492 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO