Example Needed: Change the default print method of an object

前端 未结 1 1680
广开言路
广开言路 2020-12-05 17:50

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 ob

相关标签:
1条回答
  • 2020-12-05 18:39

    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 
    
    0 讨论(0)
提交回复
热议问题