我正在创建一个导入.txt文件并返回一个文件的函数data.frame.有时我想向用户显示一条消息以跟随数据.我的问题是,通过在函数体中包含消息,它显示在数据之前,并且在data.frame具有许多行的大型中,用户可能永远不会看到它.
例如,给定:
foo=function(cars){
message('Pay attention to me!')
return(cars)
}
Run Code Online (Sandbox Code Playgroud)
如果用户输入:
foo(cars)
Run Code Online (Sandbox Code Playgroud)
该函数将显示我的消息,但仅在返回的对象之前(在这种情况下是cars来自R的base包的数据.如何message()在返回的底部显示我的内容data.frame?
我也尝试过回复邮件,但无济于事:
foo=function(cars){
return(cars,message('help!'))
}
Run Code Online (Sandbox Code Playgroud)
我注意到warning()和stop()函数都显示了它们的文本末尾data.frame,但我想显示既不是警告也不是错误的消息,而只是一个FYI.
为了澄清,理想情况下,在调用函数时将显示消息(无论输出是否分配给变量名),但每次使用结果对象时都不会显示该消息.foo(cars)应该显示消息obj=foo(cars).但就是obj不应该.
由于安德烈对我的类似问题的回答不太适用于数据帧(它返回了一个空帧),因此我对该print.bar()答案做了一个小小的调整,似乎与数据帧配合得很好(至少到目前为止)。
foo <- function(x) {
## put all your function code here - 'x' will be the return value
class(x) <- c("bar", class(x))
x
}
print.bar <- function(x, message = TRUE, ...) {
## the only difference is the absence of this line
NextMethod(x)
if(message) message("I am a message, hear me ROAR!!")
}
tail(foo(mtcars))
# mpg cyl disp hp drat wt qsec vs am gear carb
# Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.7 0 1 5 2
# Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.9 1 1 5 2
# Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.5 0 1 5 4
# Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.5 0 1 5 6
# Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.6 0 1 5 8
# Volvo 142E 21.4 4 121.0 109 4.11 2.780 18.6 1 1 4 2
# I am a message, hear me ROAR!!
Run Code Online (Sandbox Code Playgroud)
截至本次编辑,我很难实现下面注释中的请求(在进行分配然后调用对象后,在对象下没有消息打印)。suppressMessages()一种可能的解决方法是在分配时使用
obj <- suppressMessages(foo(mtcars))
Run Code Online (Sandbox Code Playgroud)
所以在控制台调用时,foo()会打印该消息。分配时obj,后续打印时不会打印该信息obj
| 归档时间: |
|
| 查看次数: |
3923 次 |
| 最近记录: |