Variables in R
Variables are used to store data, whose value can be changed according to our need. Unique name given to a variable (function and objects as well) is an identifier.
Rules for writing Identifiers in R
The rules for writing identifiers in R are:
- Identifiers can be a combination of letters, digits, period (
.
) and underscore (_
). - It must start with a letter or a period. If it starts with a period, it cannot be followed by a digit.
- Reserved words in R cannot be used as identifiers.
Valid identifiers in R
Some of the examples of valid identifiers are:
total
, Sum
, .fine.with.dot
, this_is_acceptable
, Number5
Invalid identifiers in R
Some of the invalid identifiers are:
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 constants 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)
typeof(5L)
typeof(5i)
Output
[1] "double" [1] "integer" [1] "complex"
Numeric constants preceded by 0x
or 0X
are interpreted as hexadecimal numbers.
0xff
0XF + 1
Output
[1] 255 [1] 16
Character Constants
Character constants can be represented using either single quotes (') or double quotes (") as delimiters.
'example'
typeof("5")
Output
[1] "example" [1] "character"
Built-in Constants
Some of the built-in constants defined in R along with their values are shown below.
LETTERS
letters
pi
month.name
month.abb
Output
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z" [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z" [1] 3.141593 [1] "January" "February" "March" "April" "May" "June" [7] "July" "August" "September" "October" "November" "December" [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
pi <- 56
pi
Output
[1] 3.141593 [1] 56