Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Make my R script executable?

Tags:

r

shebang

rscript

I am aware this is at high risk of being a duplicate, but in none of the other questions here I have found an answer to my problem. Below is a summary of what I have already tried.

I have an R script file file.r:

#!/usr/bin/env Rscript 
print("Hello World!")

which is executable (chmod +x file.r), and which used to run nicely (last time I used it was about a month ago) by issuing:

$ ./file.r

However, today:

$ ./file.r
/usr/bin/env: 'Rscript\r': No such file or directory

In fact:

$ which Rscript
/usr/bin/Rscript 

Thus I changed shebang to: #!/usr/bin Rscript, but:

$ ./file.r
/usr/bin: bad interpreter: Permission denied

Then I thought I would run it as super user, but:

$ sudo ./file.r
sudo: unable to execute ./file.r: Permission denied

Reading around I found that a fresh installation of R would solve my problem, so I un-installed and installed R. Unfortunately what I have written before still applies. Notice however that the following works with both shebang versions:

$ Rscript file.r
[1] "Hello World!"

What am I doing wrong?

like image 442
k88074 Avatar asked Apr 24 '17 16:04

k88074


People also ask

Can you compile an Rscript?

Overview. You don't necessary need to author an R Markdown document to create a dynamic report. In fact, you can take any R script and compile it into a report that includes commentary, source code, and script output. Reports can be compiled to any output format including HTML, PDF, MS Word, and Markdown.

How do I save an Rscript to my computer?

Saving the file To save the script, you can either click on the blue save icon, use the keyboard commands Ctrl + S on Windows or Command + S on Mac OS or go to File > Save. This file will be open in RStudio the next time you reopen RStudio unless you click on the X on the file tab to close it.

How do I run an entire Rscript in RStudio?

To run the entire document press the Ctrl+Shift+Enter key (or use the Source toolbar button).

How do I run an Rscript in bash?

Use Rscript to run R from bash R comes with Rscript , a command line tool that can run R scripts or R commands directly from the bash shell. You can run it using Rscript test. r . And even better, if you add an initial shebang line #!/usr/bin/env Rscript in the script above and make it executable with chmod +x test.


Video Answer


1 Answers

Ah, Its carriage return (\r) issue, It's added to the first line, if you are using vi editor, :set list will show it. line endings will be shown as $ and carriage return chars as ^M.

#!/usr/bin/env Rscript  Makes your script portable than #!/usr/bin/Rscript

Btw, you can insert \r in vi by going into insert(i)/Append(a) mode and type ctrl+v and then ctrl+m

like image 64
Ravi Avatar answered Oct 14 '22 17:10

Ravi