I need a bit of help with jargon, and a short piece of example code. Different types of objects have a specific way of outputting themselves when you type the name of the object and hit enter, an lm object shows a summary of the model, a vector lists the contents of the vector.
I'd like to be able to write my own way for "showing" the contents of a specific type of object. Ideally, I'd like to be able to seperate this from existing types of objects.
How would I go about doing this?
print() Syntax in Python Objects get converted to a string before printing. sep is an optional parameter that specifies how more than one object are separated. The default is ' ' – a space.
The print(Object) method of PrintStream Class in Java is used to print the specified Object on the stream. This Object is taken as a parameter. Parameters: This method accepts a mandatory parameter object which is the Object to be printed in the Stream. Return Value: This method do not returns any value.
Here's an example to get you started. Once you get the basic idea of how S3 methods are dispatched, have a look at any of the print methods returned by methods("print")
to see how you can achieve more interesting print styles.
## Define a print method that will be automatically dispatched when print() ## is called on an object of class "myMatrix" print.myMatrix <- function(x) { n <- nrow(x) for(i in seq_len(n)) { cat(paste("This is row", i, "\t: " )) cat(x[i,], "\n") } } ## Make a couple of example matrices m <- mm <- matrix(1:16, ncol=4) ## Create an object of class "myMatrix". class(m) <- c("myMatrix", class(m)) ## When typed at the command-line, the 'print' part of the read-eval-print loop ## will look at the object's class, and say "hey, I've got a method for you!" m # This is row 1 : 1 5 9 13 # This is row 2 : 2 6 10 14 # This is row 3 : 3 7 11 15 # This is row 4 : 4 8 12 16 ## Alternatively, you can specify the print method yourself. print.myMatrix(mm) # This is row 1 : 1 5 9 13 # This is row 2 : 2 6 10 14 # This is row 3 : 3 7 11 15 # This is row 4 : 4 8 12 16
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With