R Constant | Variables & Constants - r - learn r - r programming



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.
variables

Rules for writing Identifiers in R

  • 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

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

Invalid identifiers in R

[email protected], 5um, _fine, TRUE, .0ne

Best Example:

  • 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 are entities whose value cannot be altered. Basic types of constant are numeric constants and character constants.

Numeric Constants

  • Numbers 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"

Read Also

Golang Const

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



Related Searches to R Constant | Variables & Constants