打印如果未分配

时间:2012-10-24 19:32:31

标签: r

如何在函数中写入检测输出是否被赋值(<-)的方法?理由是我想打印一条消息,如果它没有被分配,只是去了控制台,但是如果被分配,我不想打印消息。

这是一个虚拟的例子以及我希望它如何表现:

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)

函数中的being_assigned是我想要检测的虚构未知条件,但不知道如何。

2 个答案:

答案 0 :(得分:14)

我认为您可以做的最好的事情是为函数返回的对象定义一个特殊的打印方法:

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

答案 1 :(得分:2)

我喜欢Josh的想法但是对于未来的海报想要展示我所做的,这是他的方法的略微修改版本。他的方法打印出类信息,这是我唯一不喜欢的。他使用NextMethod来避免无限递归打印。这导致了

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

要打印。因此,为了避免这种情况,我首先打印消息,然后通过类对象的长度打印1(使用索引)。

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

再次感谢Josh的想法。

如果读者不希望小[1]索引打印,他们可以cat输出int打印语句为:

print.beep<- function(beep) {
    cat(paste0(comment(beep), "\n"))
    cat(beep[1:length(beep)], "\n")
}
相关问题