print if not assigned

前端 未结 2 1359
余生分开走
余生分开走 2020-12-18 21:11

How can I write into a function a way to detect if the output is being assigned (<-) to something? The reasoning is I\'d like to print a message if it is no

相关标签:
2条回答
  • 2020-12-18 21:56

    I love Josh's idea but for future posters wanted to show what I did which is a slightly modified version of his approach. His approach prints out the class information which is the only thing I didn't like. He used the NextMethod to avoid the infinite recursion printing. This causes the

    attr(,"class")
    [1] "myClass"
    

    to be printed. So to avoid this I print the message first and then print 1 through the length of the class object (using indexing).

    fun <- function(x) {
        class(x) <- 'beep'
        comment(x) <- "hello world"
        return(x)
    }
    
    print.beep<- function(beep) {
        cat(paste0(comment(beep), "\n"))
        print(beep[1:length(beep)])
    }
    
    
    > fun(1:10)
    hello world
     [1]  1  2  3  4  5  6  7  8  9 10
    

    Thanks again Josh for the idea.

    If the reader didn't want the little [1] index to print either they could cat the output int he print statement as:

    print.beep<- function(beep) {
        cat(paste0(comment(beep), "\n"))
        cat(beep[1:length(beep)], "\n")
    }
    
    0 讨论(0)
  • 2020-12-18 22:01

    I think the best you can do is to define a special print method for objects returned by the function:

    ## Have your function prepend "myClass" to the class of the objects it returns
    fun <- function(x) {
        class(x) <- c("myClass", class(x))
        x
    }
    
    ## Define a print method for "myClass". It will be dispatched to 
    ## by the last step of the command line parse-eval-print cycle.
    print.myClass <- function(obj) {
        cat("message\n")
        NextMethod(obj)
    }
    
    > fun(1:10)
    message
     [1]  1  2  3  4  5  6  7  8  9 10
    attr(,"class")
    [1] "myClass"
    >
    > out <- fun(1:10)
    > 
    
    0 讨论(0)
提交回复
热议问题