EZ

Eduzan

Learning Hub

Eduzan
Eduzan / R (programming language)

Fundamentals of R

R is a leading language for statistical computing and data analysis, supported by over 10,000 free packages in the CRAN repository. Like other programming languages, R has a specific syntax that is crucial to understand to leverage its powerful features.

Before proceeding, ensure that R is installed on your system. We’ll use RStudio as our environment, though you can also use the R command prompt by executing the following command in your terminal:

$ R

Basic Hello World Program

Type the following in your R console:

cat("Hello, World!\n")

Output:

Hello, World!

You can achieve the same result using print() as follows:

print("Hello, World!")

Typically, we write our code in scripts, saved as .R files. To execute a script, save the following code as helloWorld.R and run it in the console with:

Rscript helloWorld.R

Code:

print("Hello, World!")

Output:

[1] "Hello, World!"

Syntax of R Programs

An R program consists of three primary components:

  1. Variables
  2. Comments
  3. Keywords

Variables in R

Previously, we directly printed output using print(). However, to reuse or manipulate data, we use variables. Variables act as named memory locations to store data. In R, variables can be assigned using three operators:

  • = (Simple Assignment)
  • <- (Leftward Assignment)
  • -> (Rightward Assignment)

Example:

# Simple Assignment
a = 10
print(a)

# Leftward Assignment
b <- 20
print(b)

# Rightward Assignment
30 -> c
print(c)

Output:

[1] 10
[1] 20
[1] 30

While the rightward assignment operator is available, it’s less common and might confuse some developers. Therefore, it’s advisable to use = or <- for assigning values.

Comments in R

Comments are crucial for enhancing code readability and are ignored by the R interpreter.

  • Single-line Comments: Start with #.
  • Multi-line Comments: Though R does not natively support multi-line comments, you can achieve this effect using a trick, such as enclosing text within triple quotes inside if(FALSE) blocks.

Example:

# This is a single-line comment
print("This is an example!")

if (FALSE) {
  "This is a multi-line comment."
  "It will not be executed."
}

Output:

[1] "This is an example!"

Keywords in R

Keywords are reserved words in R that hold a specific meaning and cannot be used as variable or function names.

To view all reserved keywords, use one of the following commands in your R console:

help("reserved")

Or:

?reserved

Commonly Used Keywords:

  • Control-flow and Function Declarationifelserepeatwhilefunctionforinnext, and break.
  • Boolean ConstantsTRUE and FALSE.
  • Special ValuesNaN (Not a Number), NULL (Undefined Value), and Inf (Infinity).

Example:

# Using control-flow
if (TRUE) {
  print("Condition is TRUE!")
}

# Using a special value
x <- Inf
print(x)

Output:

[1] "Condition is TRUE!"
[1] Inf
End of lesson.