Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write and execute a hello world program in file for R?

Tags:

linux

r

I did look in here: http://cran.r-project.org/doc/FAQ/R-FAQ.html#R-Programming

Wikipedia shows how to write an on the fly R program: http://en.wikipedia.org/wiki/Hello_world_program_examples#R_2

But how to execute this from a file?
What extension needs to be given?
How to compile the file then?

on Linux.


I created a file mow.R containing the following code:
cat ('Hello world!')

R says:

> source mow.R
Error: unexpected symbol in "source mow.R"
like image 542
Aquarius_Girl Avatar asked Jul 16 '12 10:07

Aquarius_Girl


1 Answers

I general you want to give your R files the .R extension.

To run a program you can start R (by typing "R" at the command prompt) and once inside the program/interpreter, you can execute your program (let's call it "so.R") with the source command. E.g.,

> source('so.R')

yields:

Hello World 

You can run the program from the Unix shell with

R CMD BATCH so.R

it will generate a file named "so.Rout" that will contain the output of your program run, especially if it contains non-trivial amounts of output. If there is a problem with the program run, the error messages etc will also be in this file so it's a good diagnostic tool. An alternative is the Rscript command which sends its output to stdout, in which case if it's long you need to capture it yourself.

There is a very useful trick, when googling for R related topics it can be tricky because R is a single character. To be effective, pre-pend "r-help:" to your search terms. E.g.,

r-help:Running a program

Here are two manuals that might be useful/help you get started:

  • Introduction to R
  • Programming in R

and also take a look at The R Manuals.

More information/FAQs, etc., can be found at the R web site itself. I have found that there is a lot of information on R (esp tutorials etc), but it can be tricky to find them. The "r-help" google trick really helps with this.

like image 189
Levon Avatar answered Oct 14 '22 20:10

Levon