One of the great things about knitr and markdown is that other people can rerun your analysis and recreate the R workspace to play with your data—all with a simple text file. Of course, that only works if your variables are defined in the .Rmd file itself or are part of an R package; otherwise you need to provide an Rdata file, or the raw data along with instructions for reading it into R. There is a more clever way however, and it’s called dput. The R function dput() writes an R value in a format fit for copy-paste action. That is, you could copy the text output of dput, and paste it into an R console to recreate the variable. Let’s look at the iris dataset as an example:

dput outputs a variable as a structure, explicitly defining the class, dimensions, row and column names, and any other relevant metadata. You could copy the output of dput and paste it into your .Rmd file, ensuring that everyone using your file has all the variables they need. Depending on your R console, it might be annoying to copy the text output. Unfortunately you can’t use writeClipboard(paste(dput(iris))), because it strips out the variable metadata. The easiest way I’ve found is to write the dput output to a temporary file from which to copy and paste, like so:

You can copy everything from the file.show window and paste it into a code chunk in your .Rmd file. To verify that everything works out, we’ll source the file and compare the data to the original variable.

Now you have an easy way to get full variable definitions into your R Markdown files.