Write the script and save it. Then go to the directory where the script was saved and run this code from terminal
Rscript script.R