How to Write from R to the Clipboard on a MAC

How to write from R to the clipboard on a mac

I don't have any machine under OS X to test it, but I think you should use just clip instead of "clip":

data <- rbind(c(1,1,2,3), c(1,1, 3, 4), c(1,4,6,7))
clip <- pipe("pbcopy", "w")
write.table(data, file=clip)
close(clip)

Here clip is an R object.

If you pass a string "clip" to the file argument R will think it is a file name, and instead of finding your data in clipboard, you will find a file in you R session working directory called "clip" with your data inside.

R: Function to copy to clipboard on Mac/OSX?

From the help file for base::connections:

Mac OS X users can use pipe("pbpaste") and pipe("pbcopy", "w") to read from and write to that system's clipboard.

R to clipboard won't work on a mac

pipe returns a connection object. You need to read from the connection.
For example

pcon <- pipe("pbpaste")
text <- paste(scan(pcon, what="character", quiet=TRUE), collapse=" ")
close(pcon)

This works on my mac.

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)

How to write to clipboard on Ubuntu/Linux in R?

Not sure if this is the best way, but here's how I could get it to work:

  1. Install xclip: sudo apt-get install xclip
  2. Read the manual: man xclip
  3. Write to X11 primary in R: write.table(1:10, pipe("xclip -i", "w"))

Update:

Note that the object passed to write.table will not be present in the clipboard until the pipe is closed. You can force the pipe to close by calling gc(). For example:

write.table(1:10, pipe("xclip -i", "w"))  # data may not be in clipboard
gc() # data written to primary clipboard

A better way to manage the connection is to use a function with on.exit(close(con)), which will close the pipe even if the write.table call throws an error. Note that you need to ensure you're writing to the clipboard you intend to use (primary is the default), based on your system setup.

write.xclip <- function(x, selection=c("primary", "secondary", "clipboard"), ...) {
if (!isTRUE(file.exists(Sys.which("xclip")[1L])))
stop("Cannot find xclip")
selection <- match.arg(selection)[1L]
con <- pipe(paste0("xclip -i -selection ", selection), "w")
on.exit(close(con))
write.table(x, con, ...)
}


Related Topics



Leave a reply



Submit