How do I copy and paste data into R from the clipboard?
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)
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")