Basic Syntax

"Hello, World!" Program

This is the typical first program for those new to a programming language. It can be used to test that the Installation of R is working and also introduce R's basic syntax using the REPL environment or running code written using a Text Editor at the Unix command line.

Inputs:

#This is a single line comment
print("Hello, World!")

Outputs:

"Hello, World!"

Variable Assignment

Operator
Description
Example

<- or = or <<-

Left Assignment

x <- 7, x = 7, x <<- 7

-> or ->>

Right Assignment

x -> 7, x ->> 7

Vectors (Classes)

Type
Example

Logical

TRUE, FALSE

Numeric

1, 55, 999

Integer

1L, 32L, 0L

Complex

2 + 3i

Character

"great", "23.4"

Unlike other languages, R does not require the use of print statements to output code, but it does allow them. To print, you can simply write code, or include the code you want to be printed in a print() statement.

Vector Assignment and Print Statement examples:

Inputs:

#Assign three colors to the "apple" variable
apple <- c('red','green','yellow')

print(apple)

#Get the class of the vector (with and without print statement)
print(class(apple))
class(apple)

Outputs:

"red"  "green"  "yellow"
"character"
"character"

Comments

We can write comments on our code, which do not run, to describe what certain lines of code or section of code do. These comments are just for the programmer- they will not appear anywhere in the output and simply explain what the code is doing or provide helpful notes.

  • To comment in R, use the “#” symbol and type your comment on the same line

  • R has no syntax for multi-line comments, so each line that is commented out needs a "#" symbol at the beginning

Resources

Last updated