[R] Writing a file to the disk

Duncan Murdoch murdoch at stats.uwo.ca
Tue Dec 11 23:25:10 CET 2007

On 11/12/2007 5:13 PM, Thomas L Jones, PhD wrote:
> I am having difficulty writing the code for the following operation:
> I have a numeric vector pred_out of length 156. (N = 156). Under Windows XP, 
> I need to write it to the disk in text format. Perhaps some kind soul would 
> provide the code fragment. The file name is sheet_vec.txt. Please see [1] 
> for the complete pathname.
> Each number to be written out has the following format:
> LL.RRRRRR where LL is the integral part and RRRRRR is the fractional part to 
> six decimal places. Example: "10.226207" The integral part, LL, is a maximum 
> of two digits long. All numbers are positive.
> Another hypothetical example:
> 10.226207
>  6.556988
>  4.395678
> etc. Each number is to be on a separate line. Please correct me if I am 
> wrong: A \n (newline) character ends each line.
> After writing the file, it can be closed but not destroyed. (What I plan to 
> do next is copy and paste the pred_out data into a spreadsheet.) Compressed 
> formats (zip, etc.) should be avoided if possible.
> Your ideas?
> Tom Jones
> [1] The full Windows pathname is:
> C:/Documents and Settings/Tom/My Documents/Election Day Study Nov 7, 06/
>   > sheet_vec.txt
> Sorry, but the pathname is too long to fit on one line.

Get the formatted numbers you want in a character vector, then use 
writeLines to write it out.  For example:

x <- rnorm(20)
text <- sprintf("%9.6f", x)
writeLines(text, file.choose())

This will open a file selection directory where you can navigate to the 
correct folder and enter the filename.  Alternatively, you could put the 
whole path to the file in place of file.choose().  As a third choice, 
you could just use "clipboard"; on Windows, this will write the text 
directly into the clipboard, and you can paste from there to your 

Duncan Murdoch

More information about the R-help mailing list