I would like to make R a little bit easier to execute system command. Something like ipython vs python. Here are some thoughts:
- Define cd function to change working directory by wrapping up the getwd and setwd
- Define an operator to wrap up the system() command so that I can run something like “$ls” to replace the system(“ls”)
The first one is easy to accomplish. However, I am stuck with the second one. I found no ways to redefine an operator in R for a string. Then I took a step back, I tried to define a sys(param). But now, I still need to input the quotation marks. e.g. I need to run sys(“ls”) instead of sys(ls) to list the directory. Is there a way to make the parameter assume it is a string even without the quotation marks? Thanks. Any suggestions are welcome.
Updated to simplify functions (remove a regexp) and add support for character input
You can use
match.callinside a function so that you can call the function without using quotation marks like this.Now, either of the following are equivalent to
system("ls -a")The
sysfunction above extracts the second component of the call which is the stuff between the parentheses. i.e.ls -aor"ls -a"in these examples. It then passes that tosystem(throughdeparsefirst if it is notcharacter)[I added support for strings because otherwise it doesn’t work with forward slashes, dots, etc. For example,
sys(ls /home)does not work, butsys("ls /home")does.]However, this still requires using parentheses 🙁
To avoid the use of parentheses, you can mask an operator. In the initial version of this answer, I showed how to mask
!which is not a good a idea. You suggested using?in the comments which could be done like this.Now, this is the same as
system("ls -a -l")But, if you need to use forward slashes, you’d have to use quotes like this
Alternatively, you could create a special binary operator
You can use it like this
If you need to use forward slashes, you have to quote the right side
A downside is that it requires exactly one argument on the right side of the operator.