I want to copy from the Ubuntu Linux clipboard into R Studio. My workflow consists of moving back and forth between R Studio and LibreOffice Calc. I've found the following code for writing to a Linux X11 clipboard, but I don't know how to read from it.
Write to X11 Linux clipboard:
clipboard <- function(x, sep="\t", row.names=FALSE, col.names=TRUE){
con <- pipe("xclip -selection clipboard -i", open="w")
write.table(x, con, sep=sep, row.names=row.names, col.names=col.names)
close(con)
}
# Examples
vec <- c(1,2,3,4)
clipboard(vec)
clipboard(vec, ",", col.names=FALSE)
clipboard(vec, " ", row.names=TRUE)
If I highlight a selection in LibreOffice Calc I'd like to paste it directly into R Studio. How do I accomplish this task? I have installed xclip in Ubuntu.
sudo apt-get install xclip
Using xclip
You just have to reverse some of the options and functions.
The options for the xclip command need to be changed to output and the function write.table needs to be changed into read.table.
For instance:
Using file()
You can use the solution provided by Anando but in the present description of that solution some details were left out.
The command
read.table("clipboard")
is effectively using the command.Internal(file(description, open, blocking, encoding, method, raw)
which splits up in several optionsThe case of Ubuntu 16.04 and maybe more general Linu:x
I could not track it down easily in the source code but based on the behaviour it seems like the "clipboard" option defaults to "X11_primary" (at least it has the same behavior in Ubuntu 16.04).
If you use
read.delim("X11_clipboard")
in place ofread.delim("clipboard")
then you get the copied text instead of the selected text.Note, that you may get an error when using X11_clipboard such as:
In that case you must install the Xmu header files on your system (that is the operating system, e.g. Ubuntu). I had this error in my case and resolved it by using
I do not know which of the two solved it. But after this, when I recompiled the R-base from the source code, then the
read.table("X11_clipboard")
worked. (I could not get it working by installing from the Ubuntu repository)Thank you A5C. The following code does work pulling clipboard data into R, although proper results are somewhat random.
It tends to work only if I hit return at the end of each line in LibreOffice Calc (a lot of work). Or if I highlight the data starting with the last row, furthest column to the right, and move up and to the left. Or if highlight the data but don't copy it. Just highlight it. Don't hit CTRL+C. Highlight the data and enter your read.delim("clipboard") command and R Studio will pull it in. Strange, but true. Otherwise I get the following error.