The Basics of R and RStudio

Part 2: Variables

RStudio
R
Tutorial
Blog
Author

William Okech

Published

June 22, 2022

Introduction

Variables are instrumental in programming because they are used as “containers” to store data values.

To assign a value to a variable, we can use <− or =. However, most R users prefer to use <−.

Variable assignment

1. Using <-

variable_1 <- 5
variable_1
[1] 5

2. Using =

variable_2 = 10
variable_2
[1] 10

3. Reverse the value and variable with ->

15 -> variable_3
variable_3
[1] 15

4. Assign two variables to one value

variable_4 <- variable_5 <- 30
variable_4
[1] 30
variable_5
[1] 30

Variable output

The output of the variable can then be obtained by:

  1. Typing the variable name and then pressing “Enter,”
  2. Typing “print” with the variable name in brackets, print(variable), and
  3. Typing “View” with the variable name in brackets, View(variable).

Both print() and View() are some of the many built-in functions1 available in R.

In RStudio, the list of variables that have been loaded can be viewed in the environment pane.

Figure 1: A screenshot of the environment pane with the stored variables.

print(variable_1)
[1] 5
View(variable_2)

Output of View() will be seen in the script pane

The assign() and rm() functions

In addition to using the assignment operators (<- and =), we can use the assign() function to assign a value to a variable.

assign("variable_6", 555)
variable_6
[1] 555

To remove the assignment of the value to the variable, either delete the variable in the “environment pane” or use the rm() function.

variable_7 <- 159
rm(variable_7)

After running rm() look at the environment pane to confirm whether variable_7 has been removed.

Naming variables

At this point, you may be wondering what conventions are used for naming variables. First, variables need to have meaningful names such as current_temp, time_24_hr, or weight_lbs. However, we need to be mindful of the variable style guide which provides us with the appropriate rules for naming variables.

Some rules to keep in mind are:

  1. R is case-sensitive (variable is not the same as Variable),
  2. Names similar to typical outputs or functions (TRUE, FALSE, if, or else) cannot be used,
  3. Appropriate variable names can contain letters, numbers, dots, and underscores. However, you cannot start with an underscore, number, or dot followed by a number.

Valid and invalid names

Valid names:

  • time_24_hr
  • .time24_hr

Invalid names:

  • _24_hr.time
  • 24_hr_time
  • .24_hr_time

Footnotes

  1. Functions are a collection of statements (organized and reusable code) that perform a specific task, and R has many built-in functions.↩︎