R Code Pattern
R is a command line driven program, means the commands evaluate and execute in the console. There is no need to compile the code. The syntax of R language is very simple and intuitive. Everything in R is an object. All the variables, data, functions are stored in the active memory in the form of objects. The result displays on the screen, also stores in an object.
When you launch R, the default prompt has (>) sign. We write and execute the command from here.
First Program
Let's print the simple 'Hello World' using the R language. Simply type the following command in R prompt.
str <- "Hello World!"
print (str)
The code and result on the R prompt looks like this -
Here, (>) cursor indicates to start the program. Every command is written after this cursor. If a statement is not complete in one line, then a plus(+) sign appears as continuation prompt. The standard assignment operator in R is <- or we can say that an object creates with the assign (<-) operator. In the output, the [1] means the first item in this line of output is item 1.
Comments in R
The comment is a developer guideline which does not visible on the screen and exists only for the human reader. The purpose of commenting is only to know in the future what you did, or guideline for future modifications. Comments are invaluable for helping the next person who understand your code to figure out problems and aware that what you were thinking when you wrote it. This is also helpful even when that person is yourself, a month from now, because generally we forget what we did one month ago. It is good practice to write comments for every function, class, property in your code.
R supports single line comment same style as in shell using # in the beginning of the statement.
# First program in R language
str <- "Hello World!"
print (str)
R Graphical User Interfaces (GUI)
Rather than using an R terminal window, we can also use GUI. There are some free GUIs available for R. Among them the most popular are -
- RStudio
- StatET
- Deducer
Removing Objects
The functions remove() and rm() are used to remove objects from the working directory.
>val <- 20
>val
[1] 20
>rm(val)
>val
Error: object 'val' not found