Reputation: 408
Whats the most effective way to write a R Datasample direct in to a File:
In Terminal, typing "R" -> R
works.
Creating a Datsample:
sample(1.00:20000.00, 10)
How could I write the result direct in to a file? I know the (normal) method:
(e.g.) ls -l > ~/Directory/file.txt
But the >
and >>
approach is the wrong way in R Console.
Upvotes: 0
Views: 220
Reputation: 193517
As mentioned in my comment, explore sink
. Here's a minimal example. In it, we tell R to start sinking the output to a file. The output is not visible in the R console here.
set.seed(1)
sink(file="sinking.txt")
sample(1.00:20000.00, 10)
sink()
The second call to sink()
stops sinking the output to a file. The output shows up in the R console as expected.
sample(1.00:20000.00, 10)
# [1] 4120 3531 13740 7681 15394 9952 14349 19832 7598 15542
sink
has other arguments too. append
lets you add values to an existing file, and split
makes it so that the output is sent to both the R console and the file. Now, we'll resume writing to the previous file. Set it to append the output to the previous file, and to display the output in the console
sink(file="sinking.txt", append=TRUE, split=TRUE)
sample(letters, 10)
# [1] "y" "f" "p" "c" "z" "i" "a" "h" "x" "v"
sink()
Let's read the file back in and see what was written.
cat(readLines("sinking.txt"), sep = "\n")
# [1] 5311 7443 11456 18162 4033 17964 18888 13212 12578 1236
# [1] "y" "f" "p" "c" "z" "i" "a" "h" "x" "v"
Upvotes: 1
Reputation: 121568
One option is to use capture.output
:
capture.output(sample(1.00:20000.00, 10),
file='~/Directory/file.txt')
This will create a file with the same output as what you see in the console.
Upvotes: 1