Basic Syntax in R Programming (original) (raw)

Last Updated : 20 Feb, 2026

R has a simple and readable syntax that makes it easy to start programming. Understanding the basic structure of R code helps you write clean and correct programs. R executes commands line by line and provides immediate output in the console.

Writing and Running Code

R code can be written in:

**Example:

R `

print("Hello, World!")

`

Output

[1] "Hello, World!"

Syntax of an R Program

An R program mainly consists of:

These components form the basic structure of any R script.

1. Variables in R

Variables are used to store values so they can be reused later in the program. In R, assignment can be done in three ways:

  1. = (Simple Assignment)
  2. <- (Leftward Assignment)
  3. -> (Rightward Assignment)

**Example:

R `

var1 = "Simple Assignment" var2 <- "Leftward Assignment!" "Rightward Assignment" -> var3

print(var1) print(var2) print(var3)

`

Output

[1] "Simple Assignment" [1] "Leftward Assignment!" [1] "Rightward Assignment"

The rightward assignment is less common and can be confusing for some programmers, so it is generally recommended to use the <- or = operator for assigning values in R.

Comments are used to explain code and improve readability. They are ignored by the R interpreter during execution.

**Example:

R `

This is a single line comment

print("This is fun!")

if(FALSE) { "This is multi-line comment which should be put inside either a single or a double quote" }

`

From the above output, we can see that both comments were ignored by the interpreter.

3. Keywords in R

Keywords are reserved words in R that have special meaning. They cannot be used as variable names or function names.

reserved_words_in_r

Reserved words in R

4. Semicolons and Multiple Statements

You can write multiple statements in one line using a semicolon ;

R `

x <- 5; y <- 6; print(x + y)

`

However, writing each statement on a new line improves readability.

5. Braces and Code Blocks

Curly braces {} are used to group multiple statements together, especially in control structures and functions.

R `

if (TRUE) { print("This is a block of code") print("Multiple lines inside braces") }

`

Output

[1] "This is a block of code" [1] "Multiple lines inside braces"

6. Object Naming Rules

my_value <- 100 value2 <- 50

`

7. Printing Output

R provides different functions to display output.

R `

print("Using print function") cat("Using cat function\n")

`

Output

[1] "Using print function" Using cat function