Clipboard reading and writing with R on the Mac

Writing R objects to the clipboard is very useful but a bit tricky on a Mac.  Try the following code to write the my.data dataframe to the clipboard and then paste to an excel spreadsheet.  This is based on a stackoverflow answer with a couple of tweaks.

my.data <- data.frame(x = c(1,1,2,3), 
                   y = c(1,1, 3, 4), 
                   z = c(1,4,6,7))
clip <- pipe("pbcopy", "w")                       
write.table(my.data, file=clip, sep = '\t', row.names = FALSE)                               
close(clip)

R to Clipboard to Excel

Figure 1: R to Clipboard to Excel

To read from the clipboard, copy some numbers from a spreadsheet and try something like:

read.table(pipe("pbpaste"), sep="\t", header=TRUE) # for a data frame

as.vector(unlist(read.table(pipe("pbpaste"), sep="\t", header=FALSE))) # for a vector

Once you have copied the data into R from the clipboard, it’s a good idea to dump it to your R script (or save it) then you can get the data again without having to go back to the clipboard.  For example to get the data from Figure 1 into R.  Copy it then, run the read.table function then dump to stdout() to get a text representation of the R object.  Execute this to get the R object back again next time you run the script.

test.df <- read.table(pipe("pbpaste"), sep="\t", header=TRUE) 
dump('test.df', file = stdout())

# output of dump (execute this part to get the test.df object without
# having to read the clipboard)
test.df <-
structure(list(x = c(1L, 1L, 2L, 3L), y = c(1L, 1L, 3L, 4L),
z = c(1L, 4L, 6L, 7L)), .Names = c("x", "y", "z"), class = "data.frame", row.names = c(NA, -4L))

 

For using the clipboard on Windows, see John Cook’s blog for excellent and thorough guidance.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s