Import data into R from Mac OS X clipboard

Did you know that it is possible to import (read) data into R directly from Mac OS X clipboard? Actually it is easier than it looks like, provided that you know how to address the Mac clipboard within the read.table function.

The trick is to use pipe files. Pipe files in R can be addressed through the pipe function. Next you need to know the proper name of the pipe file that corresponds to the Mac clipboard, which is “pbpaste”.

Once you put that all together, you have the correct syntax for the read.table command:

In other words, pipe(“pbpaste”) is the proper way to address the clipboard in Mac OS X, while in Windows that would be “clipboard”.

One caveat before you try it out. In order for the function above to work properly with HTML table copied from a web page, the table has to be properly formatted and complete. If not, read.table will complain that a row doesn’t have enough elements (saying something like: line 83 did not have 3 elements) or that values are missing.

The command above works properly with HTML tables taken from Wikipedia, Yahoo Finance (historical prices) and many other sites. Just go to the web page with the table, highlight the full range of the table (don’t forget the headers) and then copy it (cmd-C) to the clipboard. Then move back to R (or RStudio) and issue the command above. If everything goes well and you don’t get any error message, the content of the table will be available in data.

Hope you enjoyed this useful tip. Till next time!

One response to “Import data into R from Mac OS X clipboard”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.