优先级不高,但这是我经常执行的操作。所以,我想知道是否有任何方法可以抑制 dput
中表达式的输出.
library(data.table)
mtcars <- setDT(copy(mtcars))
mtcars[, dput(unique(gear))]
# c(4, 3, 5) <---- **only** this line was the expected output
# [1] 4 3 5 <---- Why is this line also returned?
dput(unique(mtcars$gear))
# c(4, 3, 5) <---- Expected output
我知道
dput(unique(mtcars$gear))
有效,所以不确定为什么它在 j
中没有按预期工作.谢谢!
最佳答案
从 dput() 文档:
dput:将 R 对象的 ASCII 文本表示写入文件或连接,或使用一个来重新创建对象。对于函数的输出:“对于 dput,第一个参数不可见”
输出中的第一行是 dput() 打印到屏幕上,第二行是使用函数的输出进行子设置返回的内容。您将从 deparse()
看到类似的行为。除了 deparse()
不会向屏幕输出任何内容,因此不会出现第一行:
mtcars[, deparse(unique(mtcars$gear))]
#[1] "c(4, 3, 5)"
dput() 行为的一个更好的例子是使用 print() 函数:
print(dput(unique(mtcars$gear)))
#c(4, 3, 5) # this line is what dput() prints to the screen
#[1] 4 3 5 # this line comes as a result of print the return value of dput()
如果你给
dput()
添加文件名函数,你会看到第一行不再打印,只有第二行(dput()
的返回值打印到屏幕上:print(dput(unique(mtcars$gear), file="xxx.txt"))
# [1] 4 3 5
在以下示例中可能更容易理解它是如何工作的:
# Define a function that prints a message and returns the object using invisible() function (which suppress the output)
my.f <- function(x) {message(x); invisible(x)}
# This will print the message, but will not print the output of the function
my.f(777)
# 777
# This will print the message and force printing the return value
print(my.f(777))
# 777
# [1] 777
dput()
以类似的方式工作,除了使用 message() 函数之外,它要么将内容打印到文件(如果提供了名称),要么将打印语句发送到标准输出。
关于r - 为什么data.table中j中的dput(object)也会打印(object)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50206745/