如何在函数中写入一种方法来检测输出是否被赋值<-给某事物?原因是我想打印一条消息,如果它没有被分配,只是去了控制台,但如果它被分配,我希望它不打印消息.
这是一个虚拟的例子以及我希望它如何表现:
fun <- function(x) {
if (being_assigned) {
print("message")
}
return(x)
}
#no assignment so message prints
> fun(6)
[1] "message"
[1] 6
#assignment so message does not prints
> x <- fun(6)
Run Code Online (Sandbox Code Playgroud)
该being_assigned函数中是虚未知状态,我想检测,但不知道怎么办.
Jos*_*ien 14
我认为你能做的最好的事情是为函数返回的对象定义一个特殊的print方法:
## 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)
>
Run Code Online (Sandbox Code Playgroud)