How do I copy and paste data into R from the clipboard?

Solution 1:

Assuming you have data in the Windows clipboard (for example, copied data from Excel), to put that data into a variable named copdat in R use:

copdat <- read.delim("clipboard")

If you want to copy data from an R variable named rdat into the Windows clipboard (for example, to copy into Excel) use:

write.table(rdat, "clipboard", sep="\t", row.names=FALSE, col.names=FALSE)

Solution 2:

The name and exact connection used for the 'clipboard' varies depending on the OS.

for Windows:

x <- read.delim("clipboard")

for Mac OS:

x <- read.delim(pipe("pbpaste"))

This works because read.delim, like many functions, will accept a range of connection types beyond just a file. For Macs we're actually using a pipe. help(connections) is pretty informative.

The psych package has a function read.clipboard() that makes this a little easier by testing for your OS.

As noted by others here, you can also write to the clipboard. There is normally a 32 K limit, which can be raised by using adding a hyphen and number after clipboard as in, for example, passing up to 256 K worth of data from object df with:

write.table(df, "clipboard-256")

Solution 3:

There's an R package / RStudio plugin called datapasta that does this very neatly - see https://CRAN.R-project.org/package=datapasta. Image below is a demonstration of its simplicity

enter image description here