May 12, 2021 R language tutorial
We'll start learning the R language programming, starting with a "Hello, World!" p rogram. D epending on your needs, you can program at the R command prompt, or you can script a program in the R language. Let's experience the differences one by one.
If you already have an R-language environment configured, you can easily turn on command prompts with just one click of the command
$ R
This will start the R language interpreter and you will get a prompt where you can start typing your program, as follows.
> myString <- "Hello, World!" > print ( myString) [1] "Hello, World!"
Here, the first statement first defines a string variable, myString, and will read "Hello, World! "
Where the assignment is given, the second sentence uses the print() statement to print the
contents of the variable myString.
Typically, you'll program by writing programs in a script file, and then using an R interpreter (called Rscript) at the command prompt to execute those scripts. S o let's start with a named test. W rite the following code in R's text file
# My first program in R Programming myString <- "Hello, World!" print ( myString)
Save the above code in test. R file, executed under the Linux command prompt, as shown below. E ven if you are using Windows or other systems, the syntax will remain the same.
$ Rscript test.R
When we run the program above, it produces the following results.
[1] "Hello, World!"
Comments can help you explain scripts in the R-language program that are ignored by the interpreter when you actually execute the program. A single comment is written at the beginning of the statement, as shown below
# My first program in R Programming
The R language does not support multi-line comments, but you can use a tip, as follows
if(FALSE) { "This is a demo for multi-line comments and it should be put inside either a single OR double quote" } myString <- "Hello, World!" print ( myString)
Although the comments above will be executed by the R interpreter, they will not interfere with your actual program. B ut you have to put single or double quotes on the content.