Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`Terminal` vs `system()` in R

Tags:

bash

macos

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.

like image 743
Remi.b Avatar asked Feb 07 '23 07:02

Remi.b


1 Answers

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/'")
like image 99
Konrad Rudolph Avatar answered Feb 09 '23 01:02

Konrad Rudolph