Using Variables in R

In R programming, we will be using variables all the time, so it is important to understand what a variable is and how it works in R.

A variable refers to a named storage that allows us to store data which our R programs can refer to and manipulate. A variable in R can store a value or an object (more on objects later). For example, we can store value ’50’ in a variable called ‘x’. This is called variable assignment, that is, the variable ‘x’ is assigned value ’50’.

The variables can be assigned values using leftward, rightward and equal to operator, however, the most common way is to use the leftward operator ( <- )

Once we have assigned a value to a variable, we can print it by just calling the variable name or by using the print() or the cat() function.

# Assignment using equal operator.
x = 50

# Assignment using leftward operator.
y <- "table"

# Assignment using rightward operator.
100 -> z

x

print (x)
cat ("x is ", x ,"\n")
cat ("y is ", y ,"\n")
cat ("z is ", z ,"\n")

When executed, this will produce the following result:

[1] 50
x is 50
y is table
z is 100

In RStudio, there are various ways you can execute the R script.

  • Select a code line and Click the ‘Run’ button in the script window. This will execute that line in the code. Select multiple lines of code and click the ‘Run’ button in the script window. This will execute all the selected lines in the code.
  • To execute the entire script (using the Source command), press CTRL+SHIFT+ENTER. This will execute the entire script with each source command printed in the console. This is called Source with Echo.
  • You can also press CTRL+SHIFT+S to run the Source command, but without Echo. This means that only the output will be printed to console, not the source commands.

This content is for paid members only.

Join our membership for lifelong unlimited access to all our data science learning content and resources.