How to write from R to the clipboard on a mac

蓝咒 提交于 2019-11-28 18:48:24
juba

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.

You can use Kmisc package, it contains 2 functions for clipboard I/O (read/write) mult-iplatform.

data <- data.frame(x1 = c(1,1,2,3), x2= c(1,1, 3, 4), x3= c(1,4,6,7))
write.cb(data)               ## wrapper to write.table in pipe("pbcopy") on MAC 
dat <- read.cb(header=T)     ## wrapper to read.table from pipe("pbpaste") on MAC
dat
  x1 x2 x3
1  1  1  1
2  1  1  4
3  2  3  6
4  3  4  7

This is an old question, but it still was a top hit when I was searching for how to get something on to the clipboard.

There is now a much better solution than any of the answers here: the clipr package.

clipr::write_clip() is all you need. It works on Windows, OS X, and X11.

From the help file: "write_clip() tries to be smart about writing objects in a useful manner. If passed a data.frame or matrix, it will format it using write.table for pasting into an external spreadsheet program. It will otherwise coerce the object to a character vector. auto will check the object type, otherwise table or character can be explicitly specified."

I also wrote a little helper function to get the last result onto the clipboard:

wc <- function(x = .Last.value) {
  clipr::write_clip(x)
}

I found this nice code to import the data in Mac directly from clipboard the answer from Marco Ghislanzoni

The trick is to use pipe files. Pipe files in R can be addressed through the pipe function. Next you need to know the proper name of the pipe file that corresponds to the Mac clipboard, which is “pbpaste”.

Once you put that all together, you have the correct syntax for the read.table command:

Importing data from Mac OS X clipboardR

data <- read.table(pipe("pbpaste"), sep="\t", header=T)

On Mac OS X try this:

copy_to_clipboard = function(x,sep="\t",col.names=T,...) { 
  write.table(x
             ,file = pipe("pbcopy")
             ,sep=sep
             ,col.names = col.names
             ,row.names = F
             ,quote = F,...)
}

and this:

paste_from_clipboard = function(sep="\t",header=T,...) {       
  read.table(pipe("pbpaste")
            ,sep=sep
            ,header=header,...) 
}

I just wrote some generic functions that work for both windows and mac. To use same parameters with windows version, they are using character vectors as input and output.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!