Remi.b Remi.b - 3 months ago 14
Linux Question

`Terminal` vs `system()` in R

I tried running the following in R

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


but it fails, while

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


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
.

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





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
.

Answer

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)\'')

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 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/'")
Comments