4.7 Exporting data
Often after you’ve wrangled your data in R, you’ll want to save your results. Here are some of the ways to export your data that I tend to use most:
Save to a CSV file with
rio::export(myObjectName, file="myFileName.csv")
and to an Excel file withrio::export(myObjectName, file="myFileName.xlsx")
. rio understands what file format you want based on the extension of the file name. There are several other available formats, including .tsv for tab-separated data, .json for JSON and .xml for XML.Save to an R binary object that makes it easy to load back into R in future sessions. There are two options.
Generic save()
will save one or more objects into a file, such as save(objectName1, objectName2, file="myfilename.RData")
. To read this data back into R, you just use the command load("myfilename.RData")
and all the objects return with the same names in the same state they had before.
You can also save a single object into a file with saveRDS(myobject, file="filename.rds")
. The logical assumption would be that loadRDS would read the file back in, but instead the command is readRDS – and in this case, just the data has been stored, not the object name. So, you need to read the data into a new object name, such as mydata <- readRDS("filename.rds")
.
There’s a third way of saving an R object specifically for R: generating the R commands that would re-create the object instead of the object with final results. The base R functions for generating an R file to re-create an object are dput() or dump(). However, I find rio::export(myobject, "mysavedfile.R) even easier to remember.
Finally, there are additional ways to save files that optimize for readability, speed, or compression, which I mention in the Additional Resources section at the end of this chapter.
You can also export an R object into your Windows or Mac clipboard with rio: rio::export(myObjectName, format = "clipboard")
. And, you can import data into R from your clipboard the same way: rio::import(file = "clipboard")
.
Bonus: rio’s convert() function lets you - you guessed it - convert one file type to another without having to manually pull the data into and then out of R. See ?convert for more info.
Final point: RStudio lets you click to import a file, without having to write code at all. This isn’t something I recommend until you’re comfortable importing from the command line, since I think it’s important to understand the code behind importing. But, I’ll admit this can be a handy shortcut.
In the Files tab of RStudio’s lower right pane, navigate to the file you want to import and click on it. You’ll see an option to either View File or Import Dataset. Choose import, and you’ll see a dialog that previews the data, allows you to modify how the data is imported, and previews the code that will be generated.
Make whatever changes you want and hit import, and your data will be pulled into R.
Next up: Some real-world data analysis at last.