print if not assigned

前端 未结 2 1370
余生分开走
余生分开走 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 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)
    > 
    

提交回复
热议问题