Writing out new files from data frame objects with R is just as easy as reading in files. R’s vector-oriented behavior is a fast and convenient way to recode data sets, so it’s perfect for reading in data, restructuring it, and writing it back out to a file.
8.3.1 Data Sets
The function for writing table-format files to your computer iswrite.table. You supply a data frame object asx, and this function writes its contents to a new file with a specified name, delimiter, and missing value string. For example, the following line takes themydatafileobject from Section 8.2 and writes it to a file:
R> write.table(x=mydatafile,file="/Users/tdavies/somenewfile.txt", sep="@",na="??",quote=FALSE,row.names=FALSE)
You providefilewith the folder location, ending in the filename you want for your new data file. This command creates a new table-format file called somenewfile.txt in the specified folder location, delimited by@and with missing values denoted with??(because you’re actually creating a new file, thefile.choosecommand doesn’t tend to be used here). Sincemydatafilehas variable names, these are automatically written to the file as a header. The optional logical argumentquotedetermines whether to encapsulate each non-numeric entry in double quotes (if you explicitly need them in your file for, say, formatting requirements of other software); request no quotes by setting the argument toFALSE. Another optional logical argument,row.names, asks whether to include the row names ofmydatafile(in this example, this would just be the numbers1to6), which you also omit withFALSE. The result- ing file, shown in Figure 8-6, can be opened in a text editor.
Likeread.csv,write.csvis a shortcut version of thewrite.tablefunction designed specifically for .csv files.
Figure 8-6: The contents of somenewfile.txt
8.3.2 Plots and Graphics Files
Plots can also be written directly to a file. In Chapter 7, you created and displayed plots in an active graphics device. This graphics device needn’t be a screen window; it can be a specified file. Instead of displaying the plot immediately on the screen, you can have R follow these steps: open a “file” graphics device, run any plotting commands to create the final plot, and close the device. R supports direct writing to .jpeg, .bmp, .png, and .tiff files using functions of the same names. For example, the following code uses these three steps to create a .jpeg file:
R> jpeg(filename="/Users/tdavies/myjpegplot.jpeg",width=600,height=600) R> plot(1:5,6:10,ylab="a nice ylab",xlab="here's an xlab",
main="a saved .jpeg plot") R> points(1:5,10:6,cex=2,pch=4,col=2) R> dev.off()
null device 1
The file graphics device is opened by a call tojpeg, where you pro- vide the intended name of the file and its folder location asfilename. By default, the dimensions of the device are set to 480 × 480 pixels, but here you change them to 600 × 600. You could also set these dimensions by supplying other units (inches, centimeters, or millimeters) towidthandheightand by specifying the unit with an optionalunitsargument. Once the file is opened, you execute any R plotting commands you need in order to create the image—this example plots some points and then includes some additional points with a second command. The final graphical result is silently writ- ten to the specified file just as it would have been displayed on the screen. When you’ve finished plotting, you must explicitly close the file device with a call todev.off(), which prints information on the remaining active device (here, “null device” can be loosely interpreted as “nothing is left open”). If
dev.off()isn’t called, then R will continue to output any subsequent plotting commands to the file, and possibly overwrite what you have there. The left plot in Figure 8-7 shows the resulting file created in this example.
Figure 8-7: R plots that have been written directly to disk: a .jpeg version (left) and a .pdf version (right) of the same plotting commands
You can also store R plots as other file types, such as PDFs (using the
pdffunction) and EPS files (using thepostscriptfunction). Though some argument names and default values are different for these functions, they follow the same basic premise. You specify a folder location, a filename, and width and height dimensions; enter your plotting commands; and then close the device withdev.off(). The right panel of Figure 8-7 shows the .pdf file created with the following code:
R> pdf(file="/Users/tdavies/mypdfplot.pdf",width=5,height=5) R> plot(1:5,6:10,ylab="a nice ylab",xlab="here's an xlab",
main="a saved .pdf plot") R> points(1:5,10:6,cex=2,pch=4,col=2) R> dev.off()
null device 1
Here, you use the same plotting commands as before, and there are just a few minor differences in the code. The argument for the file isfile(as opposed tofilename), and the units forwidthandheightdefault to inches inpdf. The difference of appearance between the two images in Figure 8-7 results primarily from these differences in width and height.
This same process also works forggplot2images. True to style, however,
ggplot2provides a convenient alternative. Theggsavefunction can be used to write the most recently plottedggplot2graphic to file and performs the device open/close action in one line.
For example, the following code creates and displays aggplot2object from a simple data set.
R> foo <- c(1.1,2,3.5,3.9,4.2) R> bar <- c(2,2.2,-1.3,0,0.2)
R> qplot(foo,bar,geom="blank")
+ geom_point(size=3,shape=8,color="darkgreen") + geom_line(color="orange",linetype=4)
Now, to save this plot to a file, all you need is the following line:
R> ggsave(filename="/Users/tdavies/mypngqplot.png") Saving 7 x 7 in image
This writes the image to a .png file in the specifiedfilenamedirectory. (Note that dimensions are reported if you don’t explicitly set them using
widthandheight; these will vary depending on the size of your graphics device.) The result is shown in Figure 8-8.
Figure 8-8: The .png file created using ggplot2’s ggsave command
Beyond just being concise,ggsaveis convenient in a few other ways. For one, you can use the same command to create a variety of image file types— the type is simply determined by the extension you supply in thefilename
argument. Also,ggsavehas a range of optional arguments if you want to con- trol the size of the image and the quality or scaling of the graphic.
For more details on saving images from base R graphics, see the?jpeg,
?pdf, and?postscripthelp files. You can consult?ggsavefor more on saving images withggplot2.