How to create and print variables in R

Overview

In this shot, we will learn to create and print variables in the R programming language. A variable is a container for storing data values.

How to create a variable

Unlike many other programming languages, R does not have a command that is used for declaring variables. However, variables are assigned a value using the <- sign. We type the variable name to return the output of the variable that we created.

Code example

# to create a variable
name <- 'Theo'
x <- 10
# to return the output of the variables
name
x

Note: In the R language, we can use the normal assignment operators, = and <-, like in any other programming language. However, the use of the = operator is limited to certain contexts.

How to print a variable

The R language is unique. It does not require the print() function to return an output. However, this does not mean that we cannot use the print() function in R. This function is only used when dealing with for loops. In R, we type the name of the variable in order to print it.

Code example

name <- 'Theo'
# without the print*) function
name
# using the print() function
print(name)
# using a for loop
for (x in 1:5) {
print( x)
}

Multiple variables

In the R language, we can create multiple variables with the same value in only one line of code.

Code example

# to assign multiple variable on one line
x <- y <- 2
x
y