首页 > 解决方案 > 如何在 Unix 系统上将剪贴板中的数据读入 R?

问题描述

我想通过简单地复制将数据从网站移动到 R 中,然后在 R 中使用扫描命令。但我需要独立于这个操作系统。我知道在 Windows 上我可以简单地使用 scan("clipboard") 和 MacOS scan(pipe("pbpaste"))。但是无论我在 Unix 上尝试什么,我都会收到一个错误“未指定协议”。

我在网上找到了一些关于此的讨论。除其他外,有人建议将命令

scan(file(description='clipboard'))
read.delim("X11_clipboard")
read.table(pipe("xclip -selection clipboard -o",open="r"))

可能有用,但对我来说都不行。

我正在使用 Linux CentOS 7。

标签: runixclipboardtransfer

解决方案


如果您查看其他 StackOverflow 问题,例如这个问题,您会看到xclip建议的以及两个方便的别名

alias setclip="xclip -selection c"
alias getclip="xclip -selection c -o"

这有力地暗示了这是如何工作的。为了测试,我安装了xclip(可用于我运行的 Ubuntu),突出显示 R 启动文本中的三行并尝试了它:

edd@rob:~$ xclip -selection c -o
R version 4.0.3 (2020-10-10) -- "Bunny-Wunnies Freak Out"
Copyright (C) 2020 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

edd@rob:~$ 

像宣传xclip的那样工作:恢复剪贴板内容,并将其打印到 stdout

要在 R 中使用它,我们只需要从输出中读取,我们可以通过pipe()连接:

> res <- readLines(pipe("xclip -selection c -o"))
> str(res)
 chr [1:19] "" ...
> res[1:3]
[1] ""                                                             
[2] "R version 4.0.3 (2020-10-10) -- \"Bunny-Wunnies Freak Out\""  
[3] "Copyright (C) 2020 The R Foundation for Statistical Computing"
> 

但即使这样也太过分了。看着??clipboard建议help(connections)有一个完整的段落(!!)关于这个,其中包括

 ‘file’ can be used with ‘description = "clipboard"’ in mode ‘&quot;r"’
 only.  This reads the X11 primary selection (see <URL:
 https://specifications.freedesktop.org/clipboards-spec/clipboards-latest.txt>),
 which can also be specified as ‘&quot;X11_primary"’ and the secondary
 selection as ‘&quot;X11_secondary"’.  On most systems the clipboard
 selection (that used by ‘Copy’ from an ‘Edit’ menu) can be
 specified as ‘&quot;X11_clipboard"’.

确实:

> res2 <- readLines(file(description="clipboard"))
Warning message:
In readLines(file(description = "clipboard")) :
  incomplete final line found on 'clipboard'
> str(res2)
 chr [1:19] "" ...
> res2[1:3]
[1] ""
[2] "R version 4.0.3 (2020-10-10) -- \"Bunny-Wunnies Freak Out\""  
[3] "Copyright (C) 2020 The R Foundation for Statistical Computing"  
> 

看起来,您仍然需要xclip从R写入剪贴板。


推荐阅读