How to Create a New Variable in R

A variable is a way to store data values. We use the “< -” operator to tie a data value to the variable. A variable name should be self-explanatory of what our variable is storing or referring to.

Creating a New Variable in R

To create a new variable in R, type the variable name and assign the data value using the assignment operator < –. For example:

#creating variables
name <- "John"
age <- 24
is_male <- TRUE
#printing variables
print(name)
print(age)
print(is_male)
Example
Creating New Variables in R.

Naming Rules of Variables in R

These are the rules for naming a variable in R:

  1. A variable name can contain numbers, alphabets, and special characters like period (.) and underscore (_).
  2. A variable name cannot begin with a number or underscore. For example, 2Student or _Fruits are not allowed. It should always start with an alphabet or a period. However, if you begin the variable name with a period, it should not be followed by a number. For example, .1Student isn’t allowed but .Student1 is allowed.
  3. A variable name cannot be the same as the reserved words or keywords. Some of the most common keywords are:
    • if
    • else
    • while
    • repeat
    • for
    • function
    • in
    • next
    • break
    • TRUE
    • FALSE
    • NULL
    • Inf
    • NaN
    • NA
    • NA_integer
    • NA_real
    • NA_complex_
    • NA_character_
  4. A variable name cannot include special characters like *, #, $ or whitespaces.

Leave a Comment