Writing data
Table of Contents
Saving plots
You have already seen how to save the most recent plot you create in ggplot2
,
using the command ggsave
. As a refresher:
ggsave("My_most_recent_plot.pdf")
You can save a plot from within RStudio using the 'Export' button in the 'Plot' window. This will give you the option of saving as a .pdf or as .png, .jpg or other image formats.
Sometimes you will want to save plots without creating them in the 'Plot' window first. Perhaps you want to make a pdf document with multiple pages: each one a different plot, for example. Or perhaps you're looping through multiple subsets of a file, plotting data from each subset, and you want to save each plot, but obviously can't stop the loop to click 'Export' for each one.
In this case you can use a more flexible approach. The function
pdf
creates a new pdf device. You can control the size and resolution
using the arguments to this function.
pdf("SibSp_vs_Age.pdf", width=12, height=4)
ggplot(data=titanic, aes(x=Age, y=Fare, colour=Survived)) +
geom_point()
# You then have to make sure to turn off the pdf device!
dev.off()
Open up this document and have a look.
The commands jpeg
, png
etc. are used similarly to produce
documents in different formats.
Writing data
At some point, you'll also want to write out data from R.
We can use the write.table
function for this, which is
very similar to read.table
or read.csv
from before.
Let's create a data-cleaning script. For this analysis, we only want to focus on the titanic data for males with first class tickets:
titanic_subset <- titanic[titanic$Sex == "male" &
titanic$Pclass == 1,]
write.table(titanic_subset,
file="data/titanic_subset.csv",
sep=","
)
Now let's have a look at the data. Provided data files aren't very large, this can be achieved easily in R by simply opening the file from the file explorer.
Hmm, that's not quite what we wanted. Where did all these quotation marks come from? Also the row numbers are meaningless.
Let's look at the help file to work out how to change this behaviour.
?write.table
By default R will wrap character vectors with quotation marks when writing out to file. It will also write out the row and column names.
Let's fix this:
write.table(
titanic_subset,
file="data/titanic_subset.csv",
sep=",", quote=FALSE, row.names=FALSE
)
Now lets look at the data again.
That looks better!