x fun(1:-6ren">
gpt4 book ai didi

r - 如果未分配则打印

转载 作者:行者123 更新时间:2023-12-03 14:54:18 25 4
gpt4 key购买 nike

如何在函数中写入一种检测输出是否被分配( <- )的方法?原因是我想打印一条消息,如果它没有被分配,只是进入控制台,但如果它被分配,我希望它不打印消息。

这是一个虚拟示例以及我希望它的行为方式:

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在函数中是我想检测但不知道如何检测的假想未知条件。

最佳答案

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

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

关于r - 如果未分配则打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13056392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com