How to declare constants in R

Asked

Viewed 339 times

7

when I went to reproduce the example of the question "How to turn a string into Date format in R?" the command

tab<-readHTMLTable(u,header=T,skip.rows=1)

failed. The error happened because in my environment it is natural to assign the T the value of the period I am analyzing. For this reason, in my environment, T is not synonymous with TRUE and the command fails.

It made me realize that I run the serious risk of accidentally typing pi = 7, which would lead to serious errors of analysis.

The question is how to declare pi as a constant?

1 answer

9


You can use the function lockBinding:

For example:

pi <- base::pi
lockBinding("pi", globalenv())

This will lock the variable pi in the constant base::pi internal in the global Environment. So if you try to define a new variable pi in the global environment with another value, the system will not leave:

pi <- 5
Error: cannot change value of locked binding for 'pi'
  • 1

    It is no longer safe for the first line to be pi <- base::pi?

  • Yeah, it’s safer, I’ll change it!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.