Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

r - Example Needed: Change the default print method of an object

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, ": " ))
        cat(x[i,], "
")
        }
}

## 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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...