Where does dput write when redirecting output with a shell?

I would like to see the result dputin the console, redirecting the output to a file with 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)

Why does it xdisplay its value on the console (as expected), but dput(x)does not work?

(I am using R 3.4.3 with RStudio version 1.1.423 on Windows 7)

+6
source share
2 answers

dputactually records the output where it was expected, but does not write it when it is expected. Executing the following code shows that the output dputremains pending until the next normal output:

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

... gives test.txt with:

[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()
+2

, . , " ", . , ...

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

All Articles