我希望dput在使用时将输出重定向到文件时在控制台中看到结果sink.
> sink(file = 'test.txt', split = TRUE)
> x <- 2^(1:4)
> x # test.txt now contains: [1] 2 4 8 16
[1] 2 4 8 16
> dput(x) # where does this return value go?
> dput(x, file = 'test.txt') # test.txt is overwritten with: c(2, 4, 6, 8)
Run Code Online (Sandbox Code Playgroud)
为什么将x它的值打印到控制台(如预期的那样),但dput(x)不是?
(我在Windows 7上使用R 3.4.3和RStudio版本1.1.423)
dput实际上是在预期的地方写入输出,但并不是在预期的时候写入。运行以下代码显示dput输出保持待处理状态,直到下一个正常输出:
sink(file = 'test.txt', split = TRUE)
x <- 2^(1:4)
x
dput(2*x,file="")
3*x
Run Code Online (Sandbox Code Playgroud)
...给出一个 test.txt :
[1] 2 4 8 16
c(4, 8, 16, 32)
[1] 6 12 24 48
Run Code Online (Sandbox Code Playgroud)
或者,运行sink()函数来关闭文件也会强制挂起输出(但会关闭连接)。
sink(file = 'test.txt', split = TRUE)
x <- 2^(1:4)
x
dput(2*x,file="")
sink()
Run Code Online (Sandbox Code Playgroud)