24

This is going to sound like a basic question but... How do I use universal constants with R?

I was used to being able to just write e or PI in matlab, and these variables were reserved for the universal constants. Are those available in R as well? How to access/use them?

Thanks

biogeek
  • 561
  • 1
  • 4
  • 13

1 Answers1

30

pi (note the lowercase) is defined but e is not, although exp(1) is obviously available.

pi
# [1] 3.141593

The small number of built-in constants are described :

?Constants

It would be possible to cure this lack-of-e problem with this code:

e <- exp(1)
lockBinding("e", globalenv())
e
#[1] 2.718282
e <- 2.5
#Error: cannot change value of locked binding for 'e'

(Thanks to Hadley for illustrating this in a different SO thread.) You probably also should go to:

?NumericConstants

Where you will read among other things: "A numeric constant immediately followed by i is regarded as an imaginary complex number."

The other important constants are TRUE and FALSE, and while T and F can be used in a clean session, T and F are not reserved and can be assigned other values, which will then provoke difficult to debug errors, so their use is deprecated. (Although, I suppose one could also use the lockBinding strategy on them as well.)

There are a few character "constants", such as the 26 item character vectors: letters, LETTERS, as well as 12 months in your locale: month.abb and month.name. The Greek letters (lower and uppercase) and some math notation can be accessed via methods described in ?plotmath.

The state.name and state.abb mentioned by Tyler below are actually part of the (USA) state dataset in the "datasets" package which is loaded by default:

library(help="datasets")

If you see an example that uses the cars, chickwts, iris or any of the other dataframes in "datasets", as many help() examples do, these objects can be assumed to be available on any R user's machine.

MichaelChirico
  • 33,841
  • 14
  • 113
  • 198
IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • 4
    Note that locking a binding in the global environment does not prevent one from masking the value in another environment. e.g. `f <- function() { T <- FALSE; T }; f()` runs without error or warning and returns `FALSE` even if `T <- TRUE` in the global environment and has been locked there. – G. Grothendieck Dec 03 '11 at 16:35
  • In addition to the constants described in ?Constants there's also state names and abbreviations with `state.name` & `state.abb` – Tyler Rinker Dec 03 '11 at 17:35