I have been trying to find a solution for this for a while but haven't found anything satisfactory yet. I write a lot of bash scripts, but sometimes I want to use R or Python as part of the script. Right now, I end up having to write two scripts; the original bash script to perform the first half of the task, and the R or Python script to perform the second half of the task. I call the R/Python script from within the bash script.
I am not satisfied with this solution because it splits my program over two files, which increases the chances of things getting out of sync, more files to track, etc.. Is there a way to write a block of text that contains the entirety of my R/Python script, and then have bash spit it out into a file and pass arguments to it & execute it? Is there an easier solution? This is more complicated than passing simple one-liners to R/Python because it usually involves creating and manipulating objects over several steps.
There are probably lots of solutions, but this one works:
#!/bin/bash
## do stuff
R --slave <<EOF
## R code
set.seed(101)
rnorm($1)
EOF
If you want the flexibility to pass additional bash arguments to R, I suggest:
#!/bin/bash
## do stuff
R --slave --args $@ <<EOF
## R code
set.seed(101)
args <- as.numeric(commandArgs(trailingOnly=TRUE))
do.call(rnorm,as.list(args))
EOF
obviously you could relax these, e.g. refer to parameters positionally
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With