使用接收器转移输出时,dput写在哪里?

时间:2018-03-05 17:23:35

标签: r

我希望在使用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)

为什么x会将其值打印到控制台(如预期的那样),但dput(x)不会?

(我在Windows 7上使用R 3.4.3和RStudio版本1.1.423)

2 个答案:

答案 0 :(得分:2)

dput实际上是在预期的位置写出输出,但是在预期时它没有写出来。 运行以下代码显示dput输出在下一个正常输出之前保持挂起状态:

sink(file = 'test.txt', split = TRUE)
x <- 2^(1:4)
x
dput(2*x,file="")
3*x

...给出一个test.txt:

[1]  2  4  8 16
c(4, 8, 16, 32)
[1]  6 12 24 48

或者,运行sink()函数关闭文件也会强制挂起输出(但会关闭连接)。

sink(file = 'test.txt', split = TRUE)
x <- 2^(1:4)
x
dput(2*x,file="")
sink()

答案 1 :(得分:1)

它只会告诉你的地方。这就是“无形中回归”的意思。你可以改变这种行为......

sink(file = "text.txt", split = TRUE)
x <- 2^(1:4)
x
# [1]  2  4  8 16
dput(x)
# returned invisibly, which is why you don't see it.
# but you can assign it to a variable

my_var <- dput(x)
my_var
# [1]  2  4  8 16

# But if you want to make it noisy, wrap it in ()
# When assigning it to a variable
(my_var <- dput(x))
# [1]  2  4  8 16

# This works even without assigning it to a variable 
(dput(x))
# [1]  2  4  8 16


# do this with your dput to sink command
(dput(x, file = "test.txt"))
# [1]  2  4  8 16

因此,总而言之,如果您希望在控制台中看到发生在幕后的事情(无论是invisible(<return statement>)还是赋值),请将其包装在{{{}的外层。 1}}