r - 如何在 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。
解决方案
如果您查看其他 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 ‘"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写入剪贴板。
推荐阅读
- kentico - 如何将带有表单控件的页面类型从 kentico 10 传输到 Xperience Core
- javascript - 添加其他类名后,CSS属性不起作用
- python - 如何使用 Python 以编程方式查找缩进错误
- r - 在 R 中按组创建集群
- java - 是否可以将文本格式化程序作为属性直接附加到文本字段?
- discord - discord.py 从 on_raw_reaction_add/remove 有效负载中获取频道 ID
- amazon-web-services - AWS Batch 在阵列配置中允许大约 25 个并发作业,而计算环境允许使用 256 个 CPU
- python - 从python中文本的开头更新打印输出
- c# - 动态 LoggingLevelSwitch 不适用于 .net 核心中的 IoC
- java - 我需要使用 selenium java 搜索 web 动态表中的特定行