如何在 Unix 系统上将剪贴板中的数据读取到 R 中?

How can I read data from the clipboard into R on a Unix system?

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

我在网上找到了一些关于这个的讨论。其中,建议命令

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

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

我正在使用 Linux CentOS 7.

如果您查看其他 Whosebug 问题,例如 this one,您会看到 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 恢复剪贴板内容,并将其打印到标准输出

要在 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 ‘"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 ‘"X11_primary"’ and the secondary
 selection as ‘"X11_secondary"’.  On most systems the clipboard
 selection (that used by ‘Copy’ from an ‘Edit’ menu) can be
 specified as ‘"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写入剪贴板