R Variables and Constants

In this article, you’ll learn about variables and constants in R. You’ll learn the best practices for using a variable in your program.

Variables in R

Variables are used to store data, whose value can be changed according to our need. Unique name given to variable (function and objects as well) is identifier.


Rules for writing Identifiers in R

  1. Identifiers can be a combination of letters, digits, period (.) and underscore (_).
  2. It must start with a letter or a period. If it starts with a period, it cannot be followed by a digit.
  3. Reserved words in R cannot be used as identifiers.

Valid identifiers in R

total, Sum, .fine.with.dot, this_is_acceptable, Number5


Invalid identifiers in R

tot@l, 5um, _fine, TRUE, .0ne


Best Practices

Earlier versions of R used underscore (_) as an assignment operator. So, the period (.) was used extensively in variable names having multiple words.

Current versions of R support underscore as a valid identifier but it is good practice to use period as word separators.

For example, a.variable.name is preferred over a_variable_name or alternatively we could use camel case as aVariableName


Constants in R

Constants, as the name suggests, are entities whose value cannot be altered. Basic types of constant are numeric constants and character constants.


Numeric Constants

All numbers fall under this category. They can be of type integer, double or complex.

It can be checked with the typeof() function.

Numeric constants followed by L are regarded as integer and those followed by i are regarded as complex.

> typeof(5)
[1] "double"
> typeof(5L)
[1] "integer"
> typeof(5i)
[1] "complex"

Numeric constants preceded by 0x or 0X are interpreted as hexadecimal numbers.

> 0xff
[1] 255
> 0XF + 1
[1] 16

Character Constants

Character constants can be represented using either single quotes (') or double quotes (") as delimiters.

> 'example'
[1] "example"
> typeof("5")
[1] "character"

Built-in Constants

Some of the built-in constants defined in R along with their values is shown below.

> LETTERS
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
[20] "T" "U" "V" "W" "X" "Y" "Z"
> letters
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"
> pi
[1] 3.141593
> month.name
[1] "January"   "February"  "March"     "April"     "May"       "June"     
[7] "July"      "August"    "September" "October"   "November"  "December" 
> month.abb
[1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"

But it is not good to rely on these, as they are implemented as variables whose values can be changed.

> pi
[1] 3.141593
> pi <- 56
> pi
[1] 56