R中的终端与系统() [英] `Terminal` vs `system()` in R

查看:46
本文介绍了R中的终端与系统()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在R中运行以下命令

I tried running the following in R

system("Message=HelloWoRld;echo $(sed 's/R/r/' <(echo ${Message}))")

但失败,而

Message=HelloWoRld
echo $(sed 's/R/r/' <(echo ${Message}))

当复制粘贴到终端中时,

可以正常工作.该问题似乎与<(..)有关.当我执行哪个bash system(哪个bash")时,我得到的是/bin/bash .

works fine when copy pasted in the terminal. The issue seems related to <(..). When I do either which bash or system("which bash"), I get /bin/bash.

为什么通过 system()或直接在终端窗口上执行的同一命令不能产生相同的输出?

Why does the same command via system() or directly on the terminal window does not yield to the same output?

仅供参考,我使用的是 Mac OS X 10.11.3 .Bash是 GNU bash版本3.2.57(1),R是 R版本3.2.3 .

FYI, I am on Mac OS X 10.11.3. Bash is GNU bash, version 3.2.57(1) and R is R version 3.2.3.

推荐答案

system 不是终端仿真器,并且未运行Bash.您的终端运行Bash.要在 system 中获得相同的效果,请在Bash中运行命令.例如

system is not a terminal emulator, and it’s not running Bash. Your terminal runs Bash. To get the same effect with system, run the command inside Bash. E.g.

system('bash -c \'echo $(date)\'')

此外,您当前的Bash命令非常复杂,并且使用了不必要的命令调用;您可以通过简单得多的方法来实现相同的目的

What’s more, your current Bash command is quite convoluted and uses unnecessary command invocations; you can achieve the same via the much simpler

sed s/R/r/ <<< $Message

@chepner提出了一个极好的观点,即另一种解决方案可以直接在 system 中使用,而无需将执行传递给Bash:

@chepner makes the excellent point that another solution can be used directly in system without need to pass execution to Bash:

system("Message=HelloWoRld; echo $Message | sed 's/R/r/'")

这篇关于R中的终端与系统()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆