繁体   English   中英

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

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

我想通过简单的复制将数据从 web 站点移动到 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。

如果您查看其他 StackOverflow 问题,例如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恢复剪贴板内容,并将其打印到 stdout

要在 R 中使用它,我们只需从 output 中读取,我们可以通过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写入剪贴板。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM