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)
Naming Rules of Variables in R
These are the rules for naming a variable in R:
- A variable name can contain numbers, alphabets, and special characters like period (.) and underscore (_).
- 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.
- A variable name cannot be the same as the reserved words or keywords. Some of the most common keywords are:
- A variable name cannot include special characters like *, #, $ or whitespaces.