I have a very basic question.
I am a new user of R, these days i am using one R package for my analysis, i have to run list of R commands of that package to get desired output.
I want to make my analysis pipeline and automate it so that i can do my work using one single R command with required parameters.
such type of work we do in shell scripts (where we add number of linux commands, awk/sed/perl lines
please provide me some link on how to do this, i would be thankful.
Suppose this was my analysis pipeline: I want to generate 10 numbers from the normal distribution with mean
MUand standard deviationSDand then do something else with them:At the moment I copy-paste these commands into the R terminal.
There are a few ways to “automate” this.
1. Write a function
I encompass my list of commands to execute into one big function, and put my parameters as function parameters:
Now within R I can just do
myFunction(1, .5, 10), reducing the number of commands I have to type to 1.2. Write a script
I could write a script file
myScript.r. This is like a bash script except it’s a list of R commands.I can either put my original list of commands in there, Or I could put my function in there plus an additional statement at the bottom
myFunction(1,.5,10).Then from within R, I can do:
and it will run all the R commands in the script.
3. From the shell
If you want to source this script from the shell, I’d suggest having a file
myScript.rwith the function inside it.Then check out Rscript (you can just
?Rscriptfrom within R). This comes installed R by default, and you use it for executing R commands from a unix/windows command line.For example:
In particular, you could combine methods 1) and 2) with
Rscriptto do something like:to run your function.
Or you could of course just include the
myFunction(1, .5, 10)in yourmyScript.R, in which case you can just doRscript myScript.R.The advantage of the former is if you wanted to do shell scripting (I only mention this because you mentioned bash scripts in your question). In a bash script we could do something like:
However I’d argue for not mixing bash scripts with R scripts – as I mentioned before, I only mention this option because you mentioned bash/unix scripts in your question.